package com.mrjy.maintain.bo;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.mrjy.activity.dao.IActivitySignupInfoDao;
import com.mrjy.activity.dto.ActivityPaidDTO;
import com.mrjy.common.dto.AdminUserDto;
import com.mrjy.common.dto.MemberListDto;
import com.mrjy.common.dto.QuestionCommentDto;
import com.mrjy.common.dto.UserHappinessDto;
import com.mrjy.common.entity.CoursePackageCommentInfo;
import com.mrjy.common.entity.CoursePackageVip;
import com.mrjy.common.entity.DistributorInfo;
import com.mrjy.common.entity.IntegralInfo;
import com.mrjy.common.entity.MenuInfo;
import com.mrjy.common.entity.MessageInfo;
import com.mrjy.common.entity.QuestionComment;
import com.mrjy.common.entity.QuestionInfo;
import com.mrjy.common.entity.RoleInfo;
import com.mrjy.common.entity.SMSSendInfo;
import com.mrjy.common.entity.SchoolInfo;
import com.mrjy.common.entity.ServiceStationInfo;
import com.mrjy.common.entity.ShareMemberInfo;
import com.mrjy.common.entity.TeacherInfoTypeRel;
import com.mrjy.common.entity.UserBalancePayment;
import com.mrjy.common.entity.UserBindEmail;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.entity.UserMemberInfo;
import com.mrjy.common.entity.UserVideoRel;
import com.mrjy.common.entity.VideoCommentInfo;
import com.mrjy.common.entity.VideoInfo;
import com.mrjy.common.entity.VideoVip;
import com.mrjy.common.util.ConstantsUtil;
import com.mrjy.common.util.DateUtil;
import com.mrjy.common.util.ExcelUtil;
import com.mrjy.common.util.ExportExcelUtil;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.common.util.HttpUtil;
import com.mrjy.common.util.MD5Encrypt;
import com.mrjy.common.util.Mail;
import com.mrjy.common.util.MailUtil;
import com.mrjy.common.util.MessyCodeUtil;
import com.mrjy.common.util.RandomUtil;
import com.mrjy.common.util.RegexUtil;
import com.mrjy.common.util.ResponseCode;
import com.mrjy.common.util.ResultUtil;
import com.mrjy.common.util.SMSTemplate;
import com.mrjy.coursepackage.dao.ICoursePackageCommentInfoDao;
import com.mrjy.coursepackage.dao.ICoursePackageInfoDao;
import com.mrjy.coursepackage.dao.ICoursePackageVipDao;
import com.mrjy.integral.dao.IHappinessInfoDao;
import com.mrjy.integral.dao.IIntegralExchangedLogDao;
import com.mrjy.integral.dao.IIntegralInfoDao;
import com.mrjy.integral.dto.IntegralExchangedLogDTO;
import com.mrjy.integral.util.IntegralEnum;
import com.mrjy.integral.util.IntegralUtil;
import com.mrjy.maintain.dao.ILabelTypeDao;
import com.mrjy.maintain.dao.IMenuInfoDao;
import com.mrjy.maintain.dao.IMessageInfoDao;
import com.mrjy.maintain.dao.IPartnerInfoDao;
import com.mrjy.maintain.dao.IRoleInfoDao;
import com.mrjy.maintain.dao.ISMSSendInfoDao;
import com.mrjy.maintain.dao.ISchoolInfoDao;
import com.mrjy.maintain.dao.IServiceStationInfoDao;
import com.mrjy.maintain.dao.ITeacherInfoTypeRelDao;
import com.mrjy.maintain.dao.IUserBalanceInfoDao;
import com.mrjy.maintain.dao.IUserBindEmailDao;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.maintain.dao.IUserMemberInfoDao;
import com.mrjy.maintain.util.RoleInfoEnum;
import com.mrjy.maintain.util.SharingProportionEnum;
import com.mrjy.payment.dao.IUserBalancePaymentDao;
import com.mrjy.queries.bo.IQuestionCommentBo;
import com.mrjy.queries.dao.IQuestionCommentDao;
import com.mrjy.queries.dao.IQuestionInfoDao;
import com.mrjy.share.dao.IDistributorInfoDao;
import com.mrjy.share.dao.IShareMemberDao;
import com.mrjy.video.dao.IUserVideoRelDao;
import com.mrjy.video.dao.IVideoCommentInfoDao;
import com.mrjy.video.dao.IVideoVipDao;
import com.mrjy.video.dto.SignInKeepDayDTO;
import com.mrjy.video.dto.StundentRankingDTO;
import com.mrjy.wechat.conts.MsConsts;
import com.mrjy.wechat.conts.WxConsts;

@Service("userInfoBo")
public class UserInfoBo implements IUserInfoBo {
	@Resource
	private IUserInfoDao userInfoDao;

	@Resource
	private IServiceStationInfoDao serviceStationInfoDao;
	@Resource
	private IUserBindEmailDao userBindEmailDao;

	@Resource
	private ISMSSendInfoDao smsSendInfoDao;

	@Resource
	private IUserMemberInfoDao userMemberInfoDao;

	@Resource
	private ILabelTypeDao labelTypeDao;

	@Resource
	private ITeacherInfoTypeRelDao teacherRelDao;

	@Resource
	private IShareMemberDao shareMemberDao;
	@Resource
	private IUserBalanceInfoDao userBalanceInfoDao;
	@Resource
	private IUserBalancePaymentDao userBalancePaymentDao;
	@Resource
	private IPartnerInfoDao partnerInfoDao;
	@Resource
	private IDistributorInfoDao distributorInfoDao;
	@Autowired
	private IAccessLogBo accessLogBo;
	@Resource
	private IMenuInfoDao menuInfoDao;
	@Resource
	private IMenuInfoBo menuInfoBo;
	@Resource
	private ISchoolInfoDao schoolInfoDao;
	@Resource
	private IRoleInfoBo roleInfoBo;
	@Resource
	private IRoleInfoDao roleInfoDao;
	@Resource
	private IHappinessInfoDao happinessInfoDao;
	@Resource
	private IQuestionCommentBo questionCommentBo;
	@Resource
	private IQuestionCommentDao questionCommentDao;
	@Resource
	private IQuestionInfoDao questionInfoDao;
	@Resource
	private IIntegralExchangedLogDao integralExchangedLogDao;
	@Resource
	private IMessageInfoDao messageInfoDao;
    @Resource
    private ICoursePackageInfoDao coursePackageInfoDao;
    @Resource
    private IUserVideoRelDao userVideoRelDao;
    @Resource
    private IVideoCommentInfoDao videoCommentInfoDao;
    @Resource
    private ICoursePackageCommentInfoDao coursePackageCommentInfoDao;
    @Resource
    private ICoursePackageVipDao coursePackageVipDao;
    @Resource
    private IVideoVipDao videoVipDao;
    @Resource
    private IActivitySignupInfoDao activitySignupInfoDao;
    @Resource
    private IIntegralInfoDao integralInfoDao ;

    @Override
    public int txmaintainAddUserInfo(UserInfo userInfo) {
		if (userInfoDao.queryByMobilePhone(userInfo.getMobilePhone()) != null) {
			return 0;
		}
		userInfo.setPassword(MD5Encrypt.encryptByMD5("123abc"));
		userInfo.setRegisterDate(new Date().getTime());

		userInfo.setDisableFlag(0);
		int count = userInfoDao.insert(userInfo);
		// 插入分类标签记录
		if (count == 1) {
			List<Integer> typeIds = userInfo.getTypeIds();
			if (typeIds != null && typeIds.size() > 0) {
				for (Integer typeId : typeIds) {
					TeacherInfoTypeRel teacherInfoRel = new TeacherInfoTypeRel();
					teacherInfoRel.setTypeId(typeId);
					teacherInfoRel.setTeacherId(userInfo.getId());
					teacherRelDao.insert(teacherInfoRel);
				}
			}
			/*//已成为普通推广者，则暂时作废，待老师身份作废后再恢复
			DistributorInfo disInfo = distributorInfoDao.queryNormalPromotorByUserId(userInfo.getId());
			if(disInfo != null){
				disInfo.setDisabledFlag(1);
				distributorInfoDao.updateById(disInfo);
			}
			// 新增一条为老师身份的推广者记录
			DistributorInfo dInfo = new DistributorInfo();
			dInfo.setUserId(userInfo.getId());
			dInfo.setDistributorName(userInfo.getUserName());
			dInfo.setMobilePhone(userInfo.getMobilePhone());
			dInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
			dInfo.setShareCode(userInfo.getRecommendCode());
			dInfo.setDistributorType("5");
			dInfo.setSharingProportion(0.4);
			dInfo.setDisabledFlag(0);

			distributorInfoDao.insert(dInfo);*/

		}
		return count;
	}

	@Override
	public int txmaintainAddTeacherInfo(UserInfo userInfo) {
		// TODO Auto-generated method stub
		if (userInfoDao.queryByEmail(userInfo.getEmail()) != null) {
			return 0;
		}
		if (userInfoDao.queryByLoginCode(userInfo.getLoginCode()) != null) {
			return 0;
		}
		if (userInfoDao.queryByMobilePhone(userInfo.getMobilePhone()) != null) {
			return 0;
		}
		if (userInfoDao.queryByRecommendCode(userInfo.getRecommendCode()) != null) {
			return 0;
		}
		userInfo.setPassword(MD5Encrypt.encryptByMD5("123abc"));
		userInfo.setRegisterDate(new Date().getTime());
		if (userInfo.getPhone() == null) {
			userInfo.setPhone("");
		}
		if (userInfo.getSex() == null) {
			userInfo.setSex("");
		}
		if (userInfo.getMobilePhone() == null) {
			userInfo.setMobilePhone("");
		}
		if (userInfo.getUserDesc() == null) {
			userInfo.setUserDesc("");
		}
		userInfo.setBirthday("");
		userInfo.setCity("");
		userInfo.setCounty("");
		userInfo.setProvince("");
		if (userInfo.getPicName() == null) {
			userInfo.setPicName("");
		}
		if (userInfo.getQq() == null) {
			userInfo.setQq("");
		}
		userInfo.setStreet("");

		userInfo.setDisableFlag(0);
		return userInfoDao.insert(userInfo);
	}

	@Override
	public UserInfo txFastAddUserInfo(UserInfo userInfo,String mobileValCode,Integer typeId) {
		SMSSendInfo smsSendInfo=new SMSSendInfo();
		smsSendInfo.setRecNum(userInfo.getMobilePhone());
		smsSendInfo.setSendCode(mobileValCode);
		smsSendInfo.setSmsCode(SMSTemplate.getTemplateID(typeId));
		// smsSendInfo.setSmsCode("SMS_16440022");
		SMSSendInfo smsSendInfoDB = smsSendInfoDao.validateSMSCode(smsSendInfo);
		if (smsSendInfoDB == null) {
			userInfo.setLoginMessage("error");
			return userInfo;
		} else if (smsSendInfoDB.getSmsSendTime().getTime() + 600000 < new Date()
				.getTime()) {
			userInfo.setLoginMessage("error");
			return userInfo;
		}
		if (StringUtils.isBlank(userInfo.getWeixinOpenid())) {
			userInfo.setLoginMessage("error");
			return userInfo;
		}
		
		UserInfo info = userInfoDao.queryByWeixinOpenid(userInfo.getWeixinOpenid());
		int row = 0 ;
		String shareCode = "";//分享码
		if (null == info) {//新增
			userInfo.setLoginCode(userInfo.getMobilePhone());
			userInfo.setUserName(userInfo.getUserName());
			if (userInfo.getPasswordSrc() != null) {
				userInfo.setPassword(MD5Encrypt.encryptByMD5(userInfo.getPasswordSrc()));
			}else {
				userInfo.setPassword(MD5Encrypt.encryptByMD5("123abc"));
			}
			userInfo.setRoleId(RoleInfoEnum.STUDENT.getRoleId());
			userInfo.setSex("");
			userInfo.setPhone("");
			userInfo.setQq("");
			userInfo.setProvince("");
			userInfo.setEmail("");
			userInfo.setBirthday("");
			userInfo.setCity("");
			userInfo.setCounty("");
			userInfo.setStreet("");
			userInfo.setRegisterDate(new Date().getTime());
			userInfo.setPicName("");
			userInfo.setUserDesc("");
			userInfo.setDisableFlag(0);

			if (StringUtils.isNotBlank(userInfo.getRecommendCode())) {
				shareCode = userInfo.getRecommendCode();
				userInfo.setRecommendCode(null);
			}
			row = userInfoDao.insert(userInfo);
		}else {//更新
			info.setLoginCode(userInfo.getMobilePhone());
			info.setUserName(userInfo.getUserName());
			if (userInfo.getPasswordSrc() != null) {
				info.setPassword(MD5Encrypt.encryptByMD5(userInfo.getPasswordSrc()));
			}else {
				info.setPassword(MD5Encrypt.encryptByMD5("123abc"));
			}
			info.setMobilePhone(userInfo.getMobilePhone());

            if(StringUtils.isNotBlank(userInfo.getRecommendCode())){
                shareCode = userInfo.getRecommendCode();
            }
            row = userInfoDao.updateById(info);
        }
        
        
        if (row ==1) {
            userInfo = userInfoDao.queryByWeixinOpenid(userInfo.getWeixinOpenid());
            userInfo.setLoginMessage("ok");
            
            //插入分销成员信息表
            //前台传过来的分享码，是推荐人的分享码
            if (StringUtils.isNotBlank(shareCode)) {
                UserInfo userInfoValidate = userInfoDao.queryByRecommendCode(shareCode);
                if (null != userInfoValidate) {
                    ShareMemberInfo sm = new ShareMemberInfo();
                    sm.setUserId(userInfo.getId());
                    sm.setShareCode(shareCode);
                    sm.setRegisterTime(new Date());
                    sm.setIsPayStatus(0);
                    shareMemberDao.insert(sm);
                }
                
            }
            
            return userInfo;
        }else {
            userInfo.setLoginMessage("error");
            return userInfo;
        }
    }

    

    @Override
    public Object txAddUserInfo(UserInfo userInfo,String mobileValCode,Integer typeId) {
    	Map<String, Object> map = new HashMap<String, Object>();
        SMSSendInfo smsSendInfo=new SMSSendInfo();
        smsSendInfo.setRecNum(userInfo.getMobilePhone());
        smsSendInfo.setSendCode(mobileValCode);
        smsSendInfo.setSmsCode(SMSTemplate.getTemplateID(typeId));
        SMSSendInfo smsSendInfoDB = smsSendInfoDao.validateSMSCode(smsSendInfo);
        if (smsSendInfoDB == null) {
            map.put("err_code", ResponseCode.PHONE_AND_VALCODE_NO_MATCH.getCode());
            map.put("err_msg", ResponseCode.PHONE_AND_VALCODE_NO_MATCH.getDesc());
            return map;
        } else if (smsSendInfoDB.getSmsSendTime().getTime() + 600000 < new Date()
                .getTime()) {
            map.put("err_code", ResponseCode.VALCODE_OUT_TIME.getCode());
            map.put("err_msg", ResponseCode.VALCODE_OUT_TIME.getDesc());
            return map;
        }
        
		userInfo.setLoginCode(userInfo.getMobilePhone());
		if (StringUtils.isNotBlank(userInfo.getPasswordSrc())) {
			userInfo.setPassword(MD5Encrypt.encryptByMD5(userInfo.getPasswordSrc()));
		}else {
			userInfo.setPassword(MD5Encrypt.encryptByMD5("123abc"));
		}
		userInfo.setRoleId(RoleInfoEnum.STUDENT.getRoleId());
		userInfo.setRegisterDate(new Date().getTime());
		if(StringUtils.isBlank(userInfo.getRecommendCode())){
			Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("num", 8);
			paramMap.put("count", 1);
			String code = userInfoDao.generateRecommendCode(paramMap);
			userInfo.setRecommendCode(code);
		}
		userInfo.setDisableFlag(0);
		int row = userInfoDao.insert(userInfo);
		if (row == 1) {
			map.put("err_code", ResponseCode.SUCCESS.getCode());
			map.put("err_msg", ResponseCode.SUCCESS.getDesc());
			map.put("userInfo", userInfo);
			return map;
		} else {
			map.put("err_code", ResponseCode.ADD_FAIL.getCode());
			map.put("err_msg", ResponseCode.ADD_FAIL.getDesc());
			return map;
		}
	}

	@Override
	public UserInfo login(UserInfo userInfo, HttpSession session) {
        if (userInfo.getLoginCode()==null || "".equals(userInfo.getLoginCode())) {
			UserInfo userInfoInDB = new UserInfo();
			userInfoInDB.setLoginMessage("loginCodeError");
			return userInfoInDB;
		}
		UserInfo userInfoInDB = userInfoDao.login(userInfo.getLoginCode());
		if (userInfoInDB == null) {
			userInfoInDB = new UserInfo();
			userInfoInDB.setLoginMessage("loginCodeError");
			return userInfoInDB;
		}
        if(userInfoInDB.getPassword() == null || userInfoInDB.getPassword().length == 0){
			userInfoInDB.setLoginMessage("passwordError");
			return userInfoInDB;
		} else {
            if(!MD5Encrypt.validatePassword(userInfo.getPasswordSrc(), userInfoInDB.getPassword())){
                userInfoInDB.setLoginMessage("passwordError");
                return userInfoInDB;
            }else{
            	userInfoInDB.setPassword(null);
            }
        }
        if(userInfoInDB.getDisableFlag()==1){   
            userInfoInDB.setLoginMessage("userDisable");
        }else{  
//            UserMemberInfo userMemberInfo=new UserMemberInfo();
//            userMemberInfo.setUserId(userInfoInDB.getId());
//            userInfoInDB.setMemberList(userMemberInfoDao.queryBySelected(userMemberInfo));
            userInfoInDB.setLoginMessage("ok");
            if (StringUtils.isNotBlank(userInfo.getLogin_way())&&userInfo.getLogin_way().equals(WxConsts.PC_LOGIN_CODE)){
                userInfoInDB.setSessionIdPC(userInfo.getSessionIdPC());
                userInfoDao.updateSessionPC(userInfoInDB);
            }else {
                userInfoInDB.setSessionId(userInfo.getSessionId());
                //userInfoInDB.setTokenId("token_" + new Date().getTime());
                userInfoDao.updateSession2(userInfoInDB);
            }

		}

		if (StringUtils.isNotBlank(userInfo.getLogin_way())) {
			userInfoInDB.setLogin_way(userInfo.getLogin_way());
		}
		return userInfoInDB;
	}

	@Override
	public String emailValidate(String email, String emailSrc) {
		UserInfo userInfo = userInfoDao.queryByEmail(email);
		if (userInfo == null) {
			return "ok";
		} else {
			if (email.equals(emailSrc)) {
				return "ok";
			}
			return "error";
		}
	}

    @Override
    public String emailBind(UserBindEmail userBindEmail,UserInfo userInfo) {
        String email = userBindEmail.getBindingEmail();
        if (userInfo == null) {
            return "userInfo_error";
        }
        if (userInfoDao.queryByEmail(email)!=null) {
            return "emailUsed";
        }else {
            String encode = RandomUtil.generateString(11) + new Date().getTime()+"_"+userInfo.getId();
//          if (b) {
                UserBindEmail paraBindEmail = new UserBindEmail();
                paraBindEmail.setUserId(userInfo.getId());
                paraBindEmail.setBindingEmail(email);
                UserBindEmail existBindEmail = userBindEmailDao.queryByUserIdEmail(paraBindEmail);
                if (existBindEmail != null) {
                    existBindEmail.setEncode(encode);
                    existBindEmail.setIp(userBindEmail.getIp());
                    existBindEmail.setExpire(DateUtil.longToString(new  Date().getTime()+86400000*3, DateUtil.FULL_DATE));
                    userBindEmailDao.updateById(existBindEmail);
                }else {
                    UserBindEmail ube = new UserBindEmail();
                    ube.setUserId(userInfo.getId());
                    ube.setEncode(encode);
                    ube.setIp(userBindEmail.getIp());
                    ube.setExpire(DateUtil.longToString(new  Date().getTime()+86400000*3, DateUtil.FULL_DATE));
                    ube.setDisableFlag(0);
                    ube.setBindingEmail(email);
                    userBindEmailDao.insert(ube);   
                }
            String loginCode = userInfo.getUserName() != null ? userInfo.getUserName() : userInfo.getMobilePhone();
            boolean b = sendMail(email, encode, loginCode);
//              userInfo.setEmail("");
//              userInfoDao.updateById(userInfo);
                if (!b) {
                    return "error";
                }
                return "ok";
//          }else {
//              return "error";
//          }
        }
    }

	@Override
	public Object sendMobilePhoneCode(String mobilePhone) {
		UserInfo userInfo = new UserInfo();
		userInfo.setMobilePhone(mobilePhone);
		UserInfo existUser = userInfoDao.queryBySafeValidate(userInfo);
		if (existUser == null) {
			return "ok";
		} else {
			return "phoneBinded";
		}
	}

	@Override
	public String txPhoneBind(UserInfo userInfo, String mobilePhoneCode) {
		UserInfo existUser = userInfoDao.queryBySafeValidate(userInfo);
		if (existUser != null) {
			return "phoneBinded";
		}
		int flag = userInfoDao.updateById(userInfo);
		if (flag > 0) {
			return "ok";
		} else {
			return "error";
		}

	}

/*  @Override
    public Object sendMobilePhoneCodeLogined(UserInfo userInfo) {
        if (userInfo == null) {
            return "userInfo_error";
        }else {
            return SMSUtil.sendPhoneMsgCode(userInfo.getMobilePhone());
        }
    }*/

	/**
	 * 发送邮件
	 * 
	 * @param email
	 * @param encode
	 * @param loginCode
	 * @return
	 */
	private boolean sendMail(String email, String encode, String loginCode) {

		String PUBLIC_DOMAIN = WxConsts.PUBLIC_DOMAIN; // 域名
         String url = PUBLIC_DOMAIN + "/phoneWeb/weInfo/emailValidBind.html?sid=" + encode;

		Mail mail = new Mail();
        mail.setHost("smtp.exmail.qq.com"); // 设置邮件服务器
        mail.setSender("mrjtjy@mrjtjy.com");
        mail.setReceiver(email); // 接收人
        mail.setUsername("mrjtjy@mrjtjy.com"); // 登录账号,一般都是和邮箱名一样
        mail.setPassword("1993Ying0319..."); // 发件人邮箱的登录密码
        mail.setSubject("明人教育科技：系统邮箱绑定");
		mail.setMessage(loginCode + "您好！请点击或者复制该链接到浏览器打开链接对您的账号进行邮箱绑定（有效时间为3天）"
				+ "<a target='_blank' href='" + url + "'> " + url + "</a>");
		return new MailUtil().send(mail);
	}

	@Override
    public String recommendCodeValidate(String recommendCode,String recommendCodeSrc) {
		if (userInfoDao.queryByRecommendCode(recommendCode) != null) {
			if (recommendCode != "" && recommendCode.equals(recommendCodeSrc)) {
				return "ok";
			}
			return "error";
		} else {
			return "ok";
		}
	}

	@Override
	public String getRecommendCode() {
		String recommendCode = RandomUtil.generateString2(4);
		UserInfo userInfo = userInfoDao.queryByRecommendCode(recommendCode);
		while (userInfo != null) {
			recommendCode = RandomUtil.generateString2(4);
			userInfo = userInfoDao.queryByRecommendCode(recommendCode);
		}
		return recommendCode;
	}

	@Override
	public String mobilePhoneValidate(String mobilePhone, String stid) {
		if (StringUtils.isBlank(mobilePhone)) {
			return "error";
		}
		UserInfo userInfo = userInfoDao.queryByMobilePhone(mobilePhone);
		if (userInfo != null) {
			if (userInfo.getId().toString().equals(stid)) {
				return "ok";
			}
			return "error";
		} else {
			return "ok";
		}
	}

	@Override
	public String updateMobilePhone(String mobilePhone, UserInfo sessionUserInfo) {
		sessionUserInfo.setMobilePhone(mobilePhone);
		int row = userInfoDao.updateById(sessionUserInfo);
		if (row != 1) {
			return "error";
		}
		return "ok";
	}

	@Override
	public Object passwordValidate(UserInfo userInfo, String passwordSrc) {
		Map<String, Object> map = new HashMap<String,Object>();
		if(userInfo == null){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录或登录超时");
			return map;
		}
		
		UserInfo ui = userInfoDao.queryPasswordById(userInfo.getId());
		if(ui == null){
			map.put("err_code", -2);
			map.put("err_msg", "用户未登录或登录超时");
			return map;
		}
		if(ui.getPassword() == null){
			map.put("err_code", -3);
			map.put("err_msg", "您的账号密码为空，请先找回密码");
			return map;
		}
		if (MD5Encrypt.validatePassword(passwordSrc, ui.getPassword())) {
			map.put("err_code", 0);
			map.put("err_msg", "验证成功");
		} else {
			map.put("err_code", 1);
			map.put("err_msg", "输入的原密码不正确");
		}
		return map;
	}

	@Override
    public Object txChangePassword(UserInfo userInfo, String passwordSrc, String passwordNew) {
		Map<String, Object> map = new HashMap<String,Object>();
		if(userInfo == null){
			map.put("err_code", -1);
			map.put("err_msg", "用户没登录或者登录失效");
			return map;
		}
		UserInfo userInfoDB = userInfoDao.queryPasswordById(userInfo.getId());
		if(userInfoDB == null){
			map.put("err_code", 1);
			map.put("err_msg", "该用户无效");
			return map;
		}
		if(userInfoDB.getPassword() == null){
			map.put("err_code", 2);
			map.put("err_msg", "该用户原本密码为空，请先找回密码");
			return map;
		}
		if (MD5Encrypt.validatePassword(passwordSrc, userInfoDB.getPassword())) {
			UserInfo userInfo2 = new UserInfo();
			userInfo2.setId(userInfo.getId());
			userInfo2.setPassword(MD5Encrypt.encryptByMD5(passwordNew));
			userInfoDao.updateById(userInfo2);
			
			//新增需求 修改密码得积分（只能得一次积分）
            IntegralInfo paramInfo = new IntegralInfo();
            paramInfo.setUserId(userInfo.getId());
            paramInfo.setInfoId(userInfo.getId());
        	//根据用户id和类型id查询其有没有记录
        	paramInfo.setTypeId(IntegralEnum.MODIFY_PASSWORD.getTypeId());
    		List<IntegralInfo> list = integralInfoDao.queryListByInfo(paramInfo);
    		if(list == null || list.size() == 0){
    			IntegralInfo integral = IntegralUtil.setIntegral(userInfo.getId()
        				, IntegralEnum.MODIFY_PASSWORD.getScore()
        				, IntegralEnum.MODIFY_PASSWORD.getTypeDesc()
        				, IntegralEnum.MODIFY_PASSWORD.getTypeId()
        				, userInfo.getId());
        		
    		}

            map.put("err_code", 0);
			map.put("err_msg", "修改密码成功");
			return map;
		} else {
			map.put("err_code", 3);
			map.put("err_msg", "原密码不正确");
			return map;
		}
	}

	@Override
	public String resetPassword(UserInfo userInfo) {
		UserInfo userInfo2 = new UserInfo();
		userInfo2.setId(userInfo.getId());
		userInfo2.setPassword(MD5Encrypt.encryptByMD5("123abc"));
		if(StringUtils.isNotBlank(userInfo.getPasswordSrc())){
			userInfo2.setPassword(MD5Encrypt.encryptByMD5(userInfo.getPasswordSrc()));
		}else{
			userInfo2.setPassword(MD5Encrypt.encryptByMD5("123abc"));
		}
		int row = userInfoDao.updateById(userInfo2);
		if (row > 0) {
			return "重置成功";
		} else {
			return "重置失败";
		}
    }
@Override
	public UserInfo updateById(UserInfo userInfo, UserInfo sessionUserInfo) {
		userInfo.setId(sessionUserInfo.getId());
		userInfo.setMobilePhone(sessionUserInfo.getMobilePhone());
		userInfo.setEmail(sessionUserInfo.getEmail());
		userInfoDao.updateById(userInfo);
		if (userInfo.getUserName() != null) {
			sessionUserInfo.setUserName(userInfo.getUserName());
		}
		// if (userInfo.getEmail()!=null) {
		// sessionUserInfo.setEmail(userInfo.getEmail());
		// }
		// if (userInfo.getMobilePhone()!=null) {
		// sessionUserInfo.setMobilePhone(userInfo.getMobilePhone());
		// }
		if (userInfo.getSex() != null) {
			sessionUserInfo.setSex(userInfo.getSex());
		}
		if (userInfo.getBirthday() != null) {
			sessionUserInfo.setBirthday(userInfo.getBirthday());
		}
		if (userInfo.getQq() != null) {
			sessionUserInfo.setQq(userInfo.getQq());
		}
		if (userInfo.getPhone() != null) {
			sessionUserInfo.setPhone(userInfo.getPhone());
		}
		if (userInfo.getProvince() != null) {
			sessionUserInfo.setProvince(userInfo.getProvince());
		}
		if (userInfo.getCity() != null) {
			sessionUserInfo.setCity(userInfo.getCity());
		}
		if (userInfo.getCounty() != null) {
			sessionUserInfo.setCounty(userInfo.getCounty());
		}
		if (userInfo.getStreet() != null) {
			sessionUserInfo.setStreet(userInfo.getStreet());
		}
		if (userInfo.getUserDesc() != null) {
			sessionUserInfo.setUserDesc(userInfo.getUserDesc());
		}
		if (userInfo.getPicName() != null) {
			sessionUserInfo.setPicName(userInfo.getPicName());
		}
		if (userInfo.getStationId() != null) {
			sessionUserInfo.setStationId(userInfo.getStationId());
            ServiceStationInfo station = serviceStationInfoDao.queryById(userInfo.getStationId());
            sessionUserInfo.setStationName(station.getStationName());
            sessionUserInfo.setStationProvince(station.getProvince());
            sessionUserInfo.setStationCity(station.getCity());
            sessionUserInfo.setStationCounty(station.getCounty());
        }
        return sessionUserInfo;
    }

	@Override
    public Map<String, Object> getMemberList(UserInfo sessionUserInfo,UserInfo userInfo) {
        if (sessionUserInfo == null) {
			return null;
		}
		/*
		 * int role = sessionUserInfo.getRoleId().intValue(); if (role != 2 &&
		 * role != 8) { return null; }
		 */
		Map<String, Object> map = new HashMap<String, Object>();
		if (userInfo.getRows() <= 0 && userInfo.getPageStart() < 0) {
			return null;
		}
		userInfo.setId(sessionUserInfo.getId());
		List<UserInfo> list = userInfoDao.queryMemberList(userInfo);
		map.put("total", userInfoDao.queryMemberListTotal(userInfo));
		map.put("rows", list);
		return map;
	}

	@Override
	public Map<String, Object> getMemberListAdmin(UserInfo sessionUserInfo,
			UserInfo userInfo) {
		if (sessionUserInfo == null) {
			return null;
		}

		Map<String, Object> map = new HashMap<String, Object>();
        if (userInfo.getRows() <= 0 && userInfo.getPageStart() <0 && userInfo.getId() == null) {
            return null;
		}
		// 时间段查询
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			if (StringUtils.isNotBlank(userInfo.getStartTime())) {
                userInfo.setStartDate(sdf.parse(userInfo.getStartTime()).getTime());
            }
			if (StringUtils.isNotBlank(userInfo.getEndTime())) {
				userInfo.setEndDate(sdf.parse(userInfo.getEndTime()).getTime());
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}

		List<UserInfo> list = userInfoDao.queryMemberList(userInfo);

		for (UserInfo u : list) {
			u.setRegisterDateString(sdf.format(new Date(u.getRegisterDate())));
		}

		map.put("total", userInfoDao.queryMemberListTotal(userInfo));
		map.put("rows", list);
		return map;
	}

	@Override
	public Map<String, Object> getMemberTotalAdmin(UserInfo sessionUserInfo,
			UserInfo userInfo) {
		if (sessionUserInfo == null) {
			return null;
		}
		/*
		 * int role = sessionUserInfo.getRoleId().intValue(); if (role != 1 &&
		 * role != 7) { return null; }
		 */
		Map<String, Object> map = new HashMap<String, Object>();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
            if(StringUtils.isNotBlank(userInfo.getStartTime()) && StringUtils.isNotBlank(userInfo.getEndTime())){
                Calendar cal = Calendar.getInstance();
				cal.setTime(sdf.parse(userInfo.getEndTime()));
				cal.add(Calendar.DATE, 1);
                userInfo.setStartDate(sdf.parse(userInfo.getStartTime()).getTime());
                userInfo.setEndDate(cal.getTime().getTime());
            }else if(StringUtils.isBlank(userInfo.getStartTime()) && StringUtils.isNotBlank(userInfo.getEndTime())){
                Calendar cal = Calendar.getInstance();
				cal.setTime(sdf.parse(userInfo.getEndTime()));
				cal.add(Calendar.DATE, 1);
				userInfo.setEndDate(cal.getTime().getTime());
            }else if(StringUtils.isNotBlank(userInfo.getStartTime()) && StringUtils.isBlank(userInfo.getEndTime())){
                userInfo.setStartDate(sdf.parse(userInfo.getStartTime()).getTime());
            }
		} catch (ParseException e) {
			e.printStackTrace();
			return map;
		}

		int total = userInfoDao.queryMemberListTotal(userInfo);
		map.put("total", total);
        float momey = userInfoDao.queryTeacherCommission(userInfo.getId())*total;
        map.put("money", (momey * 100)/100);
        return map;
	}

	@Override
	public Object exportMemberList(HttpServletResponse response,
			UserInfo sessionUserInfo, UserInfo paraInfo) {
		if (sessionUserInfo == null) {
			return "error";
		}
		UserInfo u = userInfoDao.queryById(paraInfo.getId());
        if (u == null) return "error";
        
		OutputStream out = null;
		String sheetName = u.getUserName();
		try {
			String fileName = "发展会员列表-" + sheetName
					+ DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)
					+ ".xls";
			response.setContentType("multipart/form-data");
			response.setHeader("Content-Disposition", "attachment;fileName="
					+ new String(fileName.getBytes("gb2312"), "ISO8859-1"));
			out = response.getOutputStream();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		paraInfo.setStartDate(stringToLong(paraInfo.getStartTime(), 0));
		paraInfo.setEndDate(stringToLong(paraInfo.getEndTime(), 1));

		List<MemberListDto> list = userInfoDao.exportMemberList(paraInfo);
        String[] headers = {"会员账号","用户名","手机号","注册日期","支付价格","支付方式","服务站名称","服务站地址省份","服务站城市","服务站区县"};
        ExportExcelUtil<MemberListDto> ex = new ExportExcelUtil<MemberListDto>();
		ex.exportExcel(sheetName, headers, list, out);
		return "ok";
	}

	private Long stringToLong(String dateStr, int day) {
		try {
			if (StringUtils.isNotBlank(dateStr)) {
				SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
				Calendar cal = Calendar.getInstance();
				cal.setTime(sim.parse(dateStr));
				cal.add(Calendar.DATE, day);
				return cal.getTime().getTime();
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Map<String, Object> userList(UserInfo userInfo) {
		if (userInfo.getUserName() == null || userInfo.getUserName() == "") {
		} else {
			userInfo.setUserName("%" + userInfo.getUserName() + "%");
		}
		if (userInfo.getLoginCode() == null || userInfo.getLoginCode() == "") {
		} else {
			userInfo.setLoginCode("%" + userInfo.getLoginCode() + "%");
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		// 时间段查询
		try {
            if(userInfo.getStartTime()!=null && userInfo.getEndTime()!=null){
                Calendar cal = Calendar.getInstance();
                cal.setTime(sdf.parse(userInfo.getEndTime()));
				cal.add(Calendar.DATE, 1);
                userInfo.setStartDate(sdf.parse(userInfo.getStartTime()).getTime());
                userInfo.setEndDate(cal.getTime().getTime());
            }else if(userInfo.getStartTime()==null && userInfo.getEndTime()!=null){
                Calendar cal = Calendar.getInstance();
                cal.setTime(sdf.parse(userInfo.getEndTime()));
				cal.add(Calendar.DATE, 1);
				userInfo.setEndDate(cal.getTime().getTime());
            }else if(userInfo.getStartTime()!=null && userInfo.getEndTime()==null){
                userInfo.setStartDate(sdf.parse(userInfo.getStartTime()).getTime());
            }
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", userInfoDao.countUser(userInfo));
		List<UserInfo> ulist = userInfoDao.queryPageUser(userInfo);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (UserInfo o : ulist) {
			o.setText(o.getUserName());
			o.setRegisterDateString(format.format(o.getRegisterDate()));
		}
		map.put("rows", ulist);
		return map;
	}

	@Override
	public List<UserInfo> userList(UserInfo sessionUserInfo, Integer labelId) {
		List<UserInfo> list;
		// if (labelId.intValue() == 1) {
		UserInfo userInfo = new UserInfo();
		userInfo.setLableTypeId(labelId);
		list = userInfoDao.queryTeacherList(userInfo);
		for (UserInfo u : list) {
			u.setText(u.getUserName());
		}
		return list;
		// }else if (labelId.intValue() == 2) {
		// list = userInfoDao.queryStationList();
		// for (UserInfo u : list) {
		// u.setText(u.getStationName());
		// }
		// return list;
		// } else if (labelId.intValue() == 3) {

		// return new ArrayList<UserInfo>();
		// }else {
		// return new ArrayList<UserInfo>();
		// }
	}

	@Override
	public List<UserInfo> userListNoPage(UserInfo userInfo) {

		List<UserInfo> ulist = userInfoDao.queryPageUser(userInfo);

		for (UserInfo o : ulist) {
			o.setText(o.getUserName());
		}

		return ulist;
	}

	@Override
	public UserInfo queryById(int id) {
		UserInfo info = userInfoDao.queryById(id);
		if (null != info) {
            List<TeacherInfoTypeRel> list = teacherRelDao.selectListByTeacherId(info.getId());
            List<Integer> typeIds = new ArrayList<Integer>();
            if (null != list && list.size() > 0) {
				for (TeacherInfoTypeRel teacherInfoRel : list) {
					typeIds.add(teacherInfoRel.getTypeId());
				}
				info.setTypeIds(typeIds);
			}
		}
		return info;
	}

	@Override
	public String loginCodeValidate(String loginCode, String stid) {
		UserInfo userInfo = userInfoDao.queryByLoginCode(loginCode);
		if (userInfo == null) {
			return "ok";
		} else {
			if (userInfo.getId().toString().equals(stid)) {
				return "ok";
			}
			return "error";
		}
	}

	@Override
	public int txUpdateById(UserInfo userInfo) {

		int count = userInfoDao.updateById(userInfo);
		if (count == 1) {
			// 先删除之前的记录
			teacherRelDao.deleteByTeacherId(userInfo.getId());
			// 再重新添加
            if (userInfo.getTypeIds() != null && userInfo.getTypeIds().size() > 0) {
                for (Integer typeId : userInfo.getTypeIds()) {
                    TeacherInfoTypeRel teacherInfoRel = new TeacherInfoTypeRel();
					teacherInfoRel.setTypeId(typeId);
					teacherInfoRel.setTeacherId(userInfo.getId());

					teacherRelDao.insert(teacherInfoRel);
				}
			}
            
            //新增需求 修改资料得积分（每个资料只能得一次积分）
            IntegralInfo paramInfo = new IntegralInfo();
            paramInfo.setUserId(userInfo.getId());
            paramInfo.setInfoId(userInfo.getId());
            if(StringUtils.isNotBlank(userInfo.getSex())){
            	//根据用户id和类型id查询其有没有记录
            	paramInfo.setTypeId(IntegralEnum.MODIFY_SEX.getTypeId());
        		List<IntegralInfo> list = integralInfoDao.queryListByInfo(paramInfo);
        		if(list == null || list.size() == 0){
        			IntegralInfo integral = IntegralUtil.setIntegral(userInfo.getId()
            				, IntegralEnum.MODIFY_SEX.getScore()
            				, IntegralEnum.MODIFY_SEX.getTypeDesc()
            				, IntegralEnum.MODIFY_SEX.getTypeId()
            				, userInfo.getId());
            		
        		}
            }
            if(StringUtils.isNotBlank(userInfo.getProvince())){
            	//根据用户id和类型id查询其有没有记录
            	paramInfo.setTypeId(IntegralEnum.MODIFY_AREA.getTypeId());
        		List<IntegralInfo> list = integralInfoDao.queryListByInfo(paramInfo);
        		if(list == null || list.size() == 0){
        			IntegralInfo integral = IntegralUtil.setIntegral(userInfo.getId()
            				, IntegralEnum.MODIFY_AREA.getScore()
            				, IntegralEnum.MODIFY_AREA.getTypeDesc()
            				, IntegralEnum.MODIFY_AREA.getTypeId()
            				, userInfo.getId());
            		
        		}
            }
            if(StringUtils.isNotBlank(userInfo.getUserDesc())){
            	//根据用户id和类型id查询其有没有记录
            	paramInfo.setTypeId(IntegralEnum.MODIFY_DESC.getTypeId());
        		List<IntegralInfo> list = integralInfoDao.queryListByInfo(paramInfo);
        		if(list == null || list.size() == 0){
        			IntegralInfo integral = IntegralUtil.setIntegral(userInfo.getId()
            				, IntegralEnum.MODIFY_DESC.getScore()
            				, IntegralEnum.MODIFY_DESC.getTypeDesc()
            				, IntegralEnum.MODIFY_DESC.getTypeId()
            				, userInfo.getId());
            		
        		}
            }

		}
		return count;
	}

    @Override
    public int txDeleteByIds(int[] ids){
        try{
            return userInfoDao.deleteByIds(ids);
        }catch(DataAccessException  e){
            return 0;
        }
    }
    
    @Override
    public Object updateDisableFlag(UserInfo userInfo,HttpSession session){
    	Map<String, Object> map = new HashMap<String, Object>();
    	UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (userInfo.getIds()==null||userInfo.getIds().length==0) {
			map.put("err_code", 400);
			map.put("err_msg", "请勾选要操作的记录");
			return map;
		}
        int row =  userInfoDao.updateDisableFlag(userInfo);
        if (row>0) {
        	map.put("err_code", 200);
        	map.put("err_msg", "操作成功,"+row+"条记录受影响");
		}else {
			map.put("err_code", 500);
			map.put("err_msg", "操作失败,"+row+"条记录受影响");
		}
        return map;
    }
    
    @Override
    public List<UserInfo> queryLableTypeList(){
        return userInfoDao.queryLableTypeList();
    }
    
    @Override
    public UserInfo weixinLogin(UserInfo info ,String sessionid) {
        UserInfo userInfoInDB = userInfoDao.queryByWeixinOpenid(info.getWeixinOpenid());
        if(userInfoInDB == null){
            userInfoInDB = new UserInfo();
            info.setSex(info.getSex());
            info.setProvince(info.getProvince());
            info.setUserName(info.getUserName());
            info.setCity(info.getCity());
            info.setRegisterDate(new Date().getTime());
            info.setDisableFlag(0);
            info.setSessionId(sessionid);
            info.setRoleId(RoleInfoEnum.STUDENT.getRoleId());
            info.setWeixinUnionid(info.getWeixinUnionid());
            info.setRecommendCode(userInfoDao.generateRecommendCodeOne(8));
            
            int result = userInfoDao.insert(info);
            if(result == 1){
            	//插入推广者表
            	DistributorInfo dInfo = new DistributorInfo();
            	dInfo.setUserId(info.getId());
            	dInfo.setDistributorName(info.getUserName());
            	dInfo.setCreateTime(new Timestamp(info.getRegisterDate()));
            	dInfo.setShareCode(info.getRecommendCode());
            	dInfo.setDistributorType(SharingProportionEnum.NORMAL.getDistributorType());
            	dInfo.setSharingProportion(SharingProportionEnum.NORMAL.getSharingProportion());
            	dInfo.setDisabledFlag(0);
            	distributorInfoDao.insert(dInfo);
                //userInfoInDB = userInfoDao.queryByWeixinOpenid(info.getWeixinOpenid());
            	userInfoInDB = info ;
                userInfoInDB.setLoginMessage("insert");
            }
        }else{  
            userInfoInDB.setSessionId(sessionid);
            //if(StringUtils.isBlank(userInfoInDB.getHeadImgUrl())){
                userInfoInDB.setHeadImgUrl(info.getHeadImgUrl());
           // }
            if(StringUtils.isBlank(userInfoInDB.getWeixinUnionid())){
            	userInfoInDB.setWeixinUnionid(info.getWeixinUnionid());
            }
            
            int update = userInfoDao.updateSession2(userInfoInDB);
            if(update == 1){
                userInfoInDB.setLoginMessage("update");
            }
        }   
       /* //新增需求，判断是否为学校学生，如果是，则设置学校的id和名称
        SchoolInfo si = schoolInfoDao.queryByUserId(userInfoInDB.getId());
        if(si != null){
        	userInfoInDB.setSchoolId(si.getId());
        	userInfoInDB.setSchoolName(si.getSchoolName());
        }*/
        return userInfoInDB;
    }
    
    @Override
    public String querySessionByUserId(int userId) {
        return userInfoDao.querySessionByUserId(userId);
    }


	@Override
	public String queryPCSessionByUserId(int userId) {
		return userInfoDao.queryPCSessionByUserId(userId);
	}

	@Override
	public Map<String, Object> queryPageByRoleId(UserInfo userInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", userInfoDao.countListByRoleId(userInfo));
		map.put("rows", userInfoDao.queryListByRoleId(userInfo));
		return map;
	}

	@Override
	public Object queryByMobilePhone(String mobilePhone) {
		UserInfo userInfo = userInfoDao.queryByMobilePhone(mobilePhone);
		if (null == userInfo) {
			return "error";
		}
		return userInfo;
	}

	@Override
	public Object txInsertWechatInfo(UserInfo info, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (info != null) {
			info.setRegisterDate(new Date().getTime());
			if (info.getRoleId() == null) {
				info.setRoleId(RoleInfoEnum.STUDENT.getRoleId());
			}
		}
		int result = userInfoDao.txInsertWechatInfo(info);
		if (result > 0) {
			UserInfo userInfo = userInfoDao.queryBindingUserInfoById(result);
			if (userInfo != null) {
				session.setAttribute(GlobalConstant.USER_INFO, userInfo);
			}
			if (info.getRecommendCode() != null) {// 分享码不为空，插入数据
				ShareMemberInfo memberInfo = new ShareMemberInfo();
				memberInfo.setUserId(userInfo.getId());
				memberInfo.setShareCode(info.getRecommendCode());
				memberInfo.setRegisterTime(new Date());
				memberInfo.setIsPayStatus(0);
				int insert = shareMemberDao.insert(memberInfo);
				if (insert == 1) {
					map.put("insetShareCode", "success");
				} else {
					map.put("insetShareCode", "success");
				}
			}
			map.put("message", "success");
		} else {
			map.put("message", "error");
		}
		return map;
	}

	@Override
	public UserInfo queryBindingUserInfoById(int id) {

		return userInfoDao.queryBindingUserInfoById(id);
	}

	/**
	 * 通过手机号码查询是不已被注册
	 * 
	 * @author csshui
	 * @param mobilePhone
	 * @return
	 */
	@Override
	public Object mobilePhoneValid(String mobilePhone) {
		Map<String, Object> map = new HashMap<String, Object>();
		int count = userInfoDao.mobilePhoneValid(mobilePhone);
		if (count > 0) {
			map.put("err_code", 1);
			map.put("err_msg", "已被注册使用");
		} else {
			map.put("err_code", 0);
			map.put("err_msg", "该号码可用");
		}
		return map;
	}

	/**
	 * 验证推荐码
	 */
	@Override
	public Object validShareCode(String shareCode) {
		Map<String, Object> map = new HashMap<String, Object>();
		int count = userInfoDao.selectByShareCode(shareCode);
		if (count == 0) {
			map.put("err_code", 1);
			map.put("err_msg", "该推荐码无效");
		} else {
			map.put("err_code", 0);
			map.put("err_msg", "该推荐码有效");
		}
		return map;
	}

	@Override
	public int updateById(UserInfo info) {
		if (null != info && info.getId().intValue() != 0) {
			return userInfoDao.updateById(info);
		}
		return 0;
	}

	@Override
	public UserInfo txAutoLogin(String openId, String sessionId) {
		UserInfo user = userInfoDao.queryByWeixinOpenid(openId);
		if (user != null) {
			user.setSessionId(sessionId);
			userInfoDao.updateById(user);
			user.setLoginMessage("success");
		}
		return user;
	}

	@Override
	public Object queryByOpenId(UserInfo info) {
		UserInfo userInfo = userInfoDao.queryByOpenId(info);
		if (userInfo != null) {
			if (userInfo.getMobilePhone() == null) {
				userInfo.setMessageString("unBinding");
			} else if (userInfo.getMobilePhone().equals(info.getMobilePhone())) {
				userInfo.setMessageString("match");
			} else {
				userInfo.setMessageString("unmatch");
			}
		}

		return userInfo;
	}

	@Override
	public Object queryPageTeacherByVideoDesc(UserInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();
		int total = userInfoDao.countPageTeacherByVideoDesc(info);
		List<UserInfo> list = userInfoDao.queryPageTeacherByVideoDesc(info);
		map.put("total", total);
		map.put("rows", list);
		return map;
	}

	@Override
	public Object queryPageTeacherBySortType(VideoInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();
		String whiteList = MsConsts.MINGSHI_RECOMMEND_WHITE_LIST;

		String[] split = whiteList.split(",");

		List<UserInfo> list = new ArrayList<>();

		int total = userInfoDao.countPageTeacherByVideoDesc(info);
		if ("hot".equals(info.getSortType())) {
			list = userInfoDao.queryPageTeacherByPlaytimes(info);
		} else if ("new".equals(info.getSortType())) {
			list = userInfoDao.queryPageTeacherByNewest(info);
		} else if ("recommend".equals(info.getSortType())) {
			for (String value : split) {
				info.setUserName(value);
                UserInfo userInfo1 = userInfoDao.queryPageTeacherByUserName(info);
				if (userInfo1 != null) {
					list.add(userInfo1);
				}
			}
			total = list.size();
		} else {
			map.put("err_msg", "查询失败,参数不对");
		}

		map.put("total", total);
		map.put("rows", list);
		return map;
	}

	@Override
	public Object queryPageTeacherByTypename(VideoInfo videoInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<UserInfo> list = userInfoDao.queryPageTeacherByTypename(videoInfo);
		int total = userInfoDao.countTeacherByTypename(videoInfo);
		map.put("total", total);
		map.put("rows", list);
		return map;
	}

	public Object txBindingByUnionId(UserInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();
		// 通过手机号码查询用户
        UserInfo userInfo = userInfoDao.queryByMobilePhone(info.getMobilePhone());
        if(null != userInfo && StringUtils.isNotBlank(userInfo.getWeixinUnionid())) {
            map.put("err_code", 104);
			map.put("err_msg", "该手机号码已经绑定微信");
			return map;
		}
		// 通过unionId查询userInfo
        UserInfo unionIdUserInfo = userInfoDao.queryByUnionId(info);
        if (null != unionIdUserInfo && StringUtils.isNotBlank(unionIdUserInfo.getMobilePhone())) {
            map.put("err_code", 105);
            map.put("err_msg", "该微信已经被绑定");
			return map;
		} else if (null == unionIdUserInfo) {
			map.put("err_code", 106);
			map.put("err_msg", "根据openid查询不到记录");
			return map;	
		}
		// 通过unionid查询是否为vip
		UserInfo uu = userInfoDao.isVipByUnionId(info.getWeixinUnionid());
		if (null != uu) {// vip
			if (userInfo != null) {// 老用户,保留老用户的数据
				// 会员表 user_member_info操作
				// 1.根据unionid查出来的useId查询 user_member_info
                UserMemberInfo openIdUserMemInfo = userMemberInfoDao.selectByUserId(unionIdUserInfo.getId());//肯定有值
                //2.根据mobile查出来的userId查询 user_member_info 
                UserMemberInfo mobileUserMemInfo = userMemberInfoDao.selectByUserId(userInfo.getId());
                if(null == mobileUserMemInfo){ //老用户不是vip，直接将unionid记录的userId修改成老用户的
					openIdUserMemInfo.setUserId(userInfo.getId());
					userMemberInfoDao.updateById(openIdUserMemInfo);
				} else {
					int updateCount = 0;
					if (mobileUserMemInfo.getMembershipFlag().intValue() == 1) {// 老用户为vip
                        Long addTime = openIdUserMemInfo.getEndDate() - openIdUserMemInfo.getStartDate();
                        if (mobileUserMemInfo.getEndDate() > System.currentTimeMillis() ) {//有效期是大于当前时间的
                            mobileUserMemInfo.setEndDate(mobileUserMemInfo.getEndDate() + addTime);
                        }
                        updateCount = userMemberInfoDao.updateById(mobileUserMemInfo);
                    }else{//老用户曾为vip
                        mobileUserMemInfo.setEndDate(openIdUserMemInfo.getEndDate());
                        mobileUserMemInfo.setMembershipFlag(1);//设置为会员
                        updateCount = userMemberInfoDao.updateById(mobileUserMemInfo);
                    }
					// 把openid查询的user_member_info 数据设置为disable_flag=1 逻辑删除
					if (updateCount > 0) {
						openIdUserMemInfo.setDisableFlag(1);
						userMemberInfoDao.updateById(openIdUserMemInfo);
					}
				}

				// balanlce_payment 表
                List<UserBalancePayment> list = userBalancePaymentDao.queryListByUserId(unionIdUserInfo.getId());
                if (null != list && list.size() > 0) {
					for (UserBalancePayment userBalancePayment : list) {
						userBalancePayment.setUserId(userInfo.getId());
						userBalancePaymentDao.updatePayment(userBalancePayment);
					}

				}

                userInfo.setWeixinUnionid(info.getWeixinUnionid());
				int count = userInfoDao.updateById(userInfo);
				if (count > 0) {
					// 绑定成功后，把unionid新增的数据逻辑删除
					unionIdUserInfo.setDisableFlag(1);
					userInfoDao.updateById(unionIdUserInfo);
					
					//新增手机绑定得积分
					IntegralInfo paramInfo = new IntegralInfo();
		            paramInfo.setUserId(userInfo.getId());
		            paramInfo.setInfoId(userInfo.getId());
	            	paramInfo.setTypeId(IntegralEnum.BIND_MOBILEPHONE.getTypeId());
	        		List<IntegralInfo> existList = integralInfoDao.queryListByInfo(paramInfo);
	        		if(existList == null || existList.size() == 0){
	        			IntegralInfo integral = IntegralUtil.setIntegral(userInfo.getId()
	            				, IntegralEnum.BIND_MOBILEPHONE.getScore()
	            				, IntegralEnum.BIND_MOBILEPHONE.getTypeDesc()
	            				, IntegralEnum.BIND_MOBILEPHONE.getTypeId()
	            				, userInfo.getId());
	            		
	        		}

					map.put("err_code", 0);
					map.put("err_msg", "绑定成功");
				} else {
					map.put("err_code", 201);
					map.put("err_msg", "绑定失败");
				}
			} else {// 手机未被使用,将手机绑定到unionid纪录去

				unionIdUserInfo.setMobilePhone(info.getMobilePhone());
				int count = userInfoDao.updateById(unionIdUserInfo);
				if (count > 0) {
					//新增手机绑定得积分
					IntegralInfo paramInfo = new IntegralInfo();
		            paramInfo.setUserId(unionIdUserInfo.getId());
		            paramInfo.setInfoId(unionIdUserInfo.getId());
	            	paramInfo.setTypeId(IntegralEnum.BIND_MOBILEPHONE.getTypeId());
	        		List<IntegralInfo> existList = integralInfoDao.queryListByInfo(paramInfo);
	        		if(existList == null || existList.size() == 0){
	        			IntegralInfo integral = IntegralUtil.setIntegral(unionIdUserInfo.getId()
	            				, IntegralEnum.BIND_MOBILEPHONE.getScore()
	            				, IntegralEnum.BIND_MOBILEPHONE.getTypeDesc()
	            				, IntegralEnum.BIND_MOBILEPHONE.getTypeId()
	            				, unionIdUserInfo.getId());
	            		
	        		}
					
					map.put("err_code", 0);
					map.put("err_msg", "绑定成功");
				} else {
					map.put("err_code", 201);
					map.put("err_msg", "绑定失败");
				}
			}
		} else {// 非vip
			if (userInfo != null) {// 老用户,保留老用户的数据
				userInfo.setWeixinUnionid(info.getWeixinUnionid());
				int count = userInfoDao.updateById(userInfo);
				if (count > 0) {
					// 绑定成功后，把unionid新增的数据逻辑删除
					unionIdUserInfo.setDisableFlag(1);
					userInfoDao.updateById(unionIdUserInfo);
					
					//新增手机绑定得积分
					IntegralInfo paramInfo = new IntegralInfo();
		            paramInfo.setUserId(userInfo.getId());
		            paramInfo.setInfoId(userInfo.getId());
	            	paramInfo.setTypeId(IntegralEnum.BIND_MOBILEPHONE.getTypeId());
	        		List<IntegralInfo> existList = integralInfoDao.queryListByInfo(paramInfo);
	        		if(existList == null || existList.size() == 0){
	        			IntegralInfo integral = IntegralUtil.setIntegral(userInfo.getId()
	            				, IntegralEnum.BIND_MOBILEPHONE.getScore()
	            				, IntegralEnum.BIND_MOBILEPHONE.getTypeDesc()
	            				, IntegralEnum.BIND_MOBILEPHONE.getTypeId()
	            				, userInfo.getId());
	            		
	        		}

					map.put("err_code", 0);
					map.put("err_msg", "绑定成功");
				} else {
					map.put("err_code", 201);
					map.put("err_msg", "绑定失败");
				}
			} else {// 新用户,将手机绑定到unionid纪录去

				unionIdUserInfo.setMobilePhone(info.getMobilePhone());
				int count = userInfoDao.updateById(unionIdUserInfo);
				if (count > 0) {
					//新增手机绑定得积分
					IntegralInfo paramInfo = new IntegralInfo();
		            paramInfo.setUserId(unionIdUserInfo.getId());
		            paramInfo.setInfoId(unionIdUserInfo.getId());
	            	paramInfo.setTypeId(IntegralEnum.BIND_MOBILEPHONE.getTypeId());
	        		List<IntegralInfo> existList = integralInfoDao.queryListByInfo(paramInfo);
	        		if(existList == null || existList.size() == 0){
	        			IntegralInfo integral = IntegralUtil.setIntegral(unionIdUserInfo.getId()
	            				, IntegralEnum.BIND_MOBILEPHONE.getScore()
	            				, IntegralEnum.BIND_MOBILEPHONE.getTypeDesc()
	            				, IntegralEnum.BIND_MOBILEPHONE.getTypeId()
	            				, unionIdUserInfo.getId());
	            		
	        		}
					
					map.put("err_code", 0);
					map.put("err_msg", "绑定成功");
				} else {
					map.put("err_code", 201);
					map.put("err_msg", "绑定失败");
				}
			}
		}

		return map;
	}
	@Override
	public Object txToBinding(UserInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (null == info) {
			map.put("err_code", 101);
			map.put("err_msg", "用户信息为空");
			return map;
		}
		if (StringUtils.isBlank(info.getMobilePhone())) {
			map.put("err_code", 102);
			map.put("err_msg", "用户手机号码为空");
			return map;
		}
		if (StringUtils.isBlank(info.getWeixinOpenid())) {
			map.put("err_code", 103);
			map.put("err_msg", "用户openId为空");
			return map;
		}
		// 通过手机号码查询用户
        UserInfo userInfo = userInfoDao.queryByMobilePhone(info.getMobilePhone());
        if(null != userInfo && StringUtils.isNotBlank(userInfo.getWeixinOpenid())) {
            map.put("err_code", 104);
			map.put("err_msg", "该手机号码已经绑定微信");
			return map;
		}
		// 通过openId查询userInfo
        UserInfo openIdUserInfo = userInfoDao.queryByOpenId(info);
        if (null != openIdUserInfo && StringUtils.isNotBlank(openIdUserInfo.getMobilePhone())) {
            map.put("err_code", 105);
            map.put("err_msg", "该微信已经被绑定");
			return map;
		} else if (null == openIdUserInfo) {
			map.put("err_code", 106);
			map.put("err_msg", "根据openid查询不到记录");
			return map;
		}
		// 通过openId查询是否为vip
		UserInfo uu = userInfoDao.isVipByOpenId(info.getWeixinOpenid());
		if (null != uu) {// vip
			if (userInfo != null) {// 老用户,保留老用户的数据
				// 会员表 user_member_info操作
				// 1.根据openId查出来的useId查询 user_member_info
                UserMemberInfo openIdUserMemInfo = userMemberInfoDao.selectByUserId(openIdUserInfo.getId());//肯定有值
                //2.根据mobile查出来的userId查询 user_member_info 
                UserMemberInfo mobileUserMemInfo = userMemberInfoDao.selectByUserId(userInfo.getId());
                if(null == mobileUserMemInfo){ //老用户不是vip，直接将openid记录的userId修改成老用户的
					openIdUserMemInfo.setUserId(userInfo.getId());
					userMemberInfoDao.updateById(openIdUserMemInfo);
				} else {
					int updateCount = 0;
					if (mobileUserMemInfo.getMembershipFlag().intValue() == 1) {// 老用户为vip
                        Long addTime = openIdUserMemInfo.getEndDate() - openIdUserMemInfo.getStartDate();
                        if (mobileUserMemInfo.getEndDate() > System.currentTimeMillis() ) {//有效期是大于当前时间的
                            mobileUserMemInfo.setEndDate(mobileUserMemInfo.getEndDate() + addTime);
                        }
                        updateCount = userMemberInfoDao.updateById(mobileUserMemInfo);
                    }else{//老用户曾为vip
                        mobileUserMemInfo.setEndDate(openIdUserMemInfo.getEndDate());
                        mobileUserMemInfo.setMembershipFlag(1);//设置为会员
                        updateCount = userMemberInfoDao.updateById(mobileUserMemInfo);
                    }
					// 把openid查询的user_member_info 数据设置为disable_flag=1 逻辑删除
					if (updateCount > 0) {
						openIdUserMemInfo.setDisableFlag(1);
						userMemberInfoDao.updateById(openIdUserMemInfo);
					}
				}

				// 分享表 share_member_info
				/*
				 * ShareMemberInfo openIdShareMemberInfo =
				 * shareMemberDao.queryShareCodeByUserId
				 * (openIdUserInfo.getId()); if (null != openIdShareMemberInfo)
				 * { openIdShareMemberInfo.setUserId(userInfo.getId());
				 * shareMemberDao.updateById(openIdShareMemberInfo); }
				 */
				// balanlce_payment 表
                List<UserBalancePayment> list = userBalancePaymentDao.queryListByUserId(openIdUserInfo.getId());
                if (null != list && list.size() > 0) {
					for (UserBalancePayment userBalancePayment : list) {
						userBalancePayment.setUserId(userInfo.getId());
						userBalancePaymentDao.updatePayment(userBalancePayment);
					}

				}

				userInfo.setWeixinOpenid(info.getWeixinOpenid());
				int count = userInfoDao.updateById(userInfo);
				if (count > 0) {
					// 绑定成功后，把openId新增的数据逻辑删除
					openIdUserInfo.setDisableFlag(1);
					userInfoDao.updateById(openIdUserInfo);
					
					//新增手机绑定得积分
					IntegralInfo paramInfo = new IntegralInfo();
		            paramInfo.setUserId(userInfo.getId());
		            paramInfo.setInfoId(userInfo.getId());
	            	paramInfo.setTypeId(IntegralEnum.BIND_MOBILEPHONE.getTypeId());
	        		List<IntegralInfo> existList = integralInfoDao.queryListByInfo(paramInfo);
	        		if(existList == null || existList.size() == 0){
	        			IntegralInfo integral = IntegralUtil.setIntegral(userInfo.getId()
	            				, IntegralEnum.BIND_MOBILEPHONE.getScore()
	            				, IntegralEnum.BIND_MOBILEPHONE.getTypeDesc()
	            				, IntegralEnum.BIND_MOBILEPHONE.getTypeId()
	            				, userInfo.getId());
	            		
	        		}

					map.put("err_code", 0);
					map.put("err_msg", "绑定成功");
				} else {
					map.put("err_code", 201);
					map.put("err_msg", "绑定失败");
				}
			} else {// 手机未被使用,将手机绑定到openId纪录去

				openIdUserInfo.setMobilePhone(info.getMobilePhone());
				int count = userInfoDao.updateById(openIdUserInfo);
				if (count > 0) {
					//新增手机绑定得积分
					IntegralInfo paramInfo = new IntegralInfo();
		            paramInfo.setUserId(openIdUserInfo.getId());
		            paramInfo.setInfoId(openIdUserInfo.getId());
	            	paramInfo.setTypeId(IntegralEnum.BIND_MOBILEPHONE.getTypeId());
	        		List<IntegralInfo> existList = integralInfoDao.queryListByInfo(paramInfo);
	        		if(existList == null || existList.size() == 0){
	        			IntegralInfo integral = IntegralUtil.setIntegral(openIdUserInfo.getId()
	            				, IntegralEnum.BIND_MOBILEPHONE.getScore()
	            				, IntegralEnum.BIND_MOBILEPHONE.getTypeDesc()
	            				, IntegralEnum.BIND_MOBILEPHONE.getTypeId()
	            				, openIdUserInfo.getId());
	            		
	        		}
					
					map.put("err_code", 0);
					map.put("err_msg", "绑定成功");
				} else {
					map.put("err_code", 201);
					map.put("err_msg", "绑定失败");
				}
			}
		} else {// 非vip
			if (userInfo != null) {// 老用户,保留老用户的数据
				userInfo.setWeixinOpenid(info.getWeixinOpenid());
				int count = userInfoDao.updateById(userInfo);
				if (count > 0) {
					// 绑定成功后，把openId新增的数据逻辑删除
					openIdUserInfo.setDisableFlag(1);
					userInfoDao.updateById(openIdUserInfo);
					
					//新增手机绑定得积分
					IntegralInfo paramInfo = new IntegralInfo();
		            paramInfo.setUserId(userInfo.getId());
		            paramInfo.setInfoId(userInfo.getId());
	            	paramInfo.setTypeId(IntegralEnum.BIND_MOBILEPHONE.getTypeId());
	        		List<IntegralInfo> existList = integralInfoDao.queryListByInfo(paramInfo);
	        		if(existList == null || existList.size() == 0){
	        			IntegralInfo integral = IntegralUtil.setIntegral(userInfo.getId()
	            				, IntegralEnum.BIND_MOBILEPHONE.getScore()
	            				, IntegralEnum.BIND_MOBILEPHONE.getTypeDesc()
	            				, IntegralEnum.BIND_MOBILEPHONE.getTypeId()
	            				, userInfo.getId());
	            		
	        		}

					map.put("err_code", 0);
					map.put("err_msg", "绑定成功");
				} else {
					map.put("err_code", 201);
					map.put("err_msg", "绑定失败");
				}
			} else {// 新用户,将手机绑定到openId纪录去

				openIdUserInfo.setMobilePhone(info.getMobilePhone());
				int count = userInfoDao.updateById(openIdUserInfo);
				if (count > 0) {
					//新增手机绑定得积分
					IntegralInfo paramInfo = new IntegralInfo();
		            paramInfo.setUserId(openIdUserInfo.getId());
		            paramInfo.setInfoId(openIdUserInfo.getId());
	            	paramInfo.setTypeId(IntegralEnum.BIND_MOBILEPHONE.getTypeId());
	        		List<IntegralInfo> existList = integralInfoDao.queryListByInfo(paramInfo);
	        		if(existList == null || existList.size() == 0){
	        			IntegralInfo integral = IntegralUtil.setIntegral(openIdUserInfo.getId()
	            				, IntegralEnum.BIND_MOBILEPHONE.getScore()
	            				, IntegralEnum.BIND_MOBILEPHONE.getTypeDesc()
	            				, IntegralEnum.BIND_MOBILEPHONE.getTypeId()
	            				, openIdUserInfo.getId());
	            		
	        		}
					
					map.put("err_code", 0);
					map.put("err_msg", "绑定成功");
				} else {
					map.put("err_code", 201);
					map.put("err_msg", "绑定失败");
				}
			}
		}

		return map;
	}

	@Override
	public Object validateMobilePhone(String mobilePhone, String openId) {
		Map<String, Object> map = new HashMap<String, Object>();
        if(StringUtils.isNotBlank(mobilePhone) && StringUtils.isNotBlank(openId)){
            UserInfo info = new UserInfo();
			info.setWeixinOpenid(openId);
			UserInfo existUserInfo = userInfoDao.queryByOpenId(info);
			if (existUserInfo != null) {
				if (StringUtils.isNotBlank(existUserInfo.getMobilePhone())) {
					map.put("err_code", 1);
					map.put("err_msg", "您已经绑定过手机");
				} else {
                    UserInfo validPhone =  userInfoDao.queryByMobilePhone(mobilePhone);
                    if(validPhone !=null){
                        if(StringUtils.isNotBlank(validPhone.getWeixinOpenid())){
							if (validPhone.getWeixinOpenid().equals(openId)) {
								map.put("err_code", 1);
								map.put("err_msg", "您已经绑定过手机");
							} else {
								map.put("err_code", 2);
								map.put("err_msg", "手机号已被绑定");
							}
						} else {
							map.put("err_code", 0);
							map.put("err_msg", "可以绑定");
						}
					} else {
						map.put("err_code", 0);
						map.put("err_msg", "可以绑定");
					}

				}
			}
		} else {
			map.put("err_code", -1);
			map.put("err_msg", "手机号或openId为空");
		}

		return map;
	}

	@Override
	public Object isVipByOpenId(String openId) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo info = userInfoDao.isVipByOpenId(openId);
		if (info != null) {
			map.put("err_code", 0);// vip
			map.put("err_msg", "会员");
		} else {
			map.put("err_code", 1);// no-vip
			map.put("err_msg", "非会员");
		}
		return map;
	}

	@Override
	public Object getTeacherInfoById(int id) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo info = userInfoDao.getTeacherInfoById(id);
		if (info != null) {

			map.put("info", info);
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
		} else {
			map.put("err_code", 1);
			map.put("err_msg", "查询异常");
		}
		return map;
	}

	@Override
	public Object getPageTeacherByName(UserInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();
        if (null != info && StringUtils.isNotBlank(info.getUserName()) && (!MessyCodeUtil.isChinese(info.getUserName().charAt(0)))) {
            info.setUserName(info.getUserName());
		}
		int result = userInfoDao.countTeacherByName(info);
		if (result > 0) {
			List<UserInfo> list = userInfoDao.getPageTeacherByName(info);
			map.put("rows", list);
		}
		map.put("total", result);
		return map;
	}

	@Override
	public Object isBindedByOpenId(String openId) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo info = userInfoDao.isBindedByOpenId(openId);
		if (null != info) {
			if (StringUtils.isBlank(info.getMobilePhone())) {
				map.put("err_code", 0);
				map.put("err_msg", "该openId未绑定手机号");
			} else {
				map.put("err_code", 1);
				map.put("err_msg", "该openId已绑定手机号");
			}
		} else {
			map.put("err_code", -1);
			map.put("err_msg", "通过openId查询无数据");
		}
		return map;
	}

	@SuppressWarnings("unchecked")
	public Object weChatToBindMobilePhone(String openId, String mobilePhone,
			String mobilePhoneCode, Integer typeId) {
		Map<String, Object> map = new HashMap<String, Object>();

		SMSSendInfo smsSendInfo = new SMSSendInfo();
		smsSendInfo.setRecNum(mobilePhone);
		smsSendInfo.setSendCode(mobilePhoneCode);
		smsSendInfo.setSmsCode(SMSTemplate.getTemplateID(typeId));
		// SMSTemplate sms = SMSTemplate.TEMPLATE_01;
		// smsSendInfo.setSmsCode("SMS_16440022");
		SMSSendInfo smsSendInfoDB = smsSendInfoDao.validateSMSCode(smsSendInfo);
		if (smsSendInfoDB == null) {
			map.put("err_code", -1);
			map.put("err_msg", "验证码错误");
			return map;
        } else if (smsSendInfoDB.getSmsSendTime().getTime() + 600000 < new Date().getTime()) {
            map.put("err_code", -2);
			map.put("err_msg", "验证码失效");
			return map;
		}
		// 绑定操作
		UserInfo info = new UserInfo();
		info.setMobilePhone(mobilePhone);
		info.setWeixinOpenid(openId);
		map = (Map<String, Object>) txToBinding(info);

		return map;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> bingPhoneByUnionId(String mobilePhone,
			String mobilePhoneCode, Integer typeId,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(userInfo == null ){
			map.put("err_code", ResponseCode.USER_ERROR.getCode());
			map.put("err_msg", ResponseCode.USER_ERROR.getDesc());
			return map;
		}
		if(StringUtils.isBlank(mobilePhoneCode) || StringUtils.isBlank(mobilePhoneCode) || StringUtils.isBlank(userInfo.getWeixinUnionid())){
			map.put("err_code", ResponseCode.ERROR_ARGS.getCode());
			map.put("err_msg", ResponseCode.ERROR_ARGS.getDesc());
			return map;
		}
		
		SMSSendInfo smsSendInfo = new SMSSendInfo();
		smsSendInfo.setRecNum(mobilePhone);
		smsSendInfo.setSendCode(mobilePhoneCode);
		smsSendInfo.setSmsCode(SMSTemplate.getTemplateID(typeId));
		SMSSendInfo smsSendInfoDB = smsSendInfoDao.validateSMSCode(smsSendInfo);
		if (smsSendInfoDB == null) {
			map.put("err_code", -1);
			map.put("err_msg", "验证码错误");
			return map;
		}else if(smsSendInfoDB.getSmsSendTime().getTime() + 600000 < new Date().getTime()){
			map.put("err_code", -2);
			map.put("err_msg", "验证码失效");
			return map;
		}
		
		// 绑定操作
		userInfo.setMobilePhone(mobilePhone);
		map = (Map<String, Object>) txBindingByUnionId(userInfo);
		
		if (map != null && (int) map.get("err_code") == 0) {// 绑定成功，用openId查询最新记录并缓存在session
			//session.invalidate();
			UserInfo userInfoPro = userInfoDao.queryByWeixinUnionid(userInfo.getWeixinUnionid());
			if (null != userInfo) {
				userInfoPro.setSessionId(session.getId());
				userInfoDao.updateById(userInfoPro);
				session.setAttribute(GlobalConstant.USER_INFO, userInfoDao);
			}
		}
		return map;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Object commomToBindMobilePhone(String id, String mobilePhone,
			String mobilePhoneCode, int typeId) {
		Map<String, Object> map = new HashMap<String, Object>();

		SMSSendInfo smsSendInfo = new SMSSendInfo();
		smsSendInfo.setRecNum(mobilePhone);
		smsSendInfo.setSendCode(mobilePhoneCode);
		smsSendInfo.setSmsCode(SMSTemplate.getTemplateID(typeId));
		SMSSendInfo smsSendInfoDB = smsSendInfoDao.validateSMSCode(smsSendInfo);
		if (smsSendInfoDB == null) {
			map.put("err_code", -1);
			map.put("err_msg", "验证码错误");
			return map;
        } else if (smsSendInfoDB.getSmsSendTime().getTime() + 600000 < new Date().getTime()) {
            map.put("err_code", -2);
			map.put("err_msg", "验证码失效");
			return map;
		}
		// 绑定操作
		UserInfo info = new UserInfo();
		info.setMobilePhone(mobilePhone);
		info.setId(Integer.parseInt(id));
		UserInfo userInfo = userInfoDao.queryByMobilePhone(mobilePhone);
		if (userInfo != null) {
			map.put("err_code", -101);
			map.put("err_msg", "手机号码已经被绑定");
			return map;
		}
		int i = userInfoDao.updateById(info);
		if (userInfo == null) {
			map.put("err_code", i);
			map.put("err_msg", "手机号码绑定成功");
			return map;
		}
		return map;
	}

	@Override
	public UserInfo queryByWeixinOpenid(String weixinOpenid) {
		return userInfoDao.queryByWeixinOpenid(weixinOpenid);
	}

	@Override
	public Object queryPageTeacherByOrderNum(UserInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<UserInfo> list = userInfoDao.queryPageTeacherByOrderNum(info);
		map.put("rows", list);
		return map;
	}

	@Override
	public Object registerForPC(UserInfo info, String mobileValCode, int typeId) {
		Map<String, Object> map = new HashMap<String, Object>();

        UserInfo userInfo=userInfoDao.queryByMobilePhone(info.getMobilePhone());
        if (userInfo!=null) {
			map.put("err_code", -3);
			map.put("err_msg", "用户已经存在");
			return map;
		}
		SMSSendInfo smsSendInfo = new SMSSendInfo();
		smsSendInfo.setRecNum(info.getMobilePhone());
		smsSendInfo.setSendCode(mobileValCode);
		smsSendInfo.setSmsCode(SMSTemplate.getTemplateID(typeId));
		// smsSendInfo.setSmsCode("SMS_16440022");

		SMSSendInfo smsSendInfoDB = smsSendInfoDao.validateSMSCode(smsSendInfo);
		if (smsSendInfoDB == null) {
			map.put("err_code", -1);
			map.put("err_msg", "验证码错误");
			return map;
        } else if (smsSendInfoDB.getSmsSendTime().getTime() + 600000 < new Date().getTime()) {
            map.put("err_code", -2);
			map.put("err_msg", "验证码失效");
			return map;
		}
		// 插入新用户
		String newPassword = new String(info.getPassword());
		byte[] md5 = MD5Encrypt.encryptByMD5(newPassword);
		info.setPassword(md5);
        info.setLoginCode(info.getMobilePhone()+"_"+RandomUtil.generateString2(3));
        info.setRoleId(RoleInfoEnum.STUDENT.getRoleId());
		info.setDisableFlag(0);
		info.setPicName("avator.png");
		info.setRegisterDate(new Date().getTime());
		int code = userInfoDao.insert(info);
		// 绑定操作
		map.put("err_code", code);
		map.put("err_msg", "注册成功");
		return map;
	}

	@Override
	public Object txInsertShareCodeByUserId(UserInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (null == info || null == info.getId()) {
			map.put("err_code", -1);
			map.put("err_msg", "用户信息不存在");
			return map;
		}

		UserInfo existInfo = userInfoDao.selectUserById(info.getId());
		if (existInfo != null) {

			// 判断该用户是什么身份
			String distributorType = "0";
			Double sharingProportion = SharingProportionEnum.NORMAL.getSharingProportion();
			/*
			 * if(existInfo.getRoleId() == 2){//导师 distributorType = "5";
			 * sharingProportion = 0.25;//0.25 }else
			 * if(StringUtils.isBlank(existInfo.getMobilePhone())){
			 * distributorType = "0"; sharingProportion = 0.10; }else
			 * if(StringUtils.isNotBlank(existInfo.getMobilePhone())){ boolean
			 * flag = false; //合作方 PartnerInfoDTO pDTO =
			 * partnerInfoDao.selectByMobilePhone(existInfo.getMobilePhone());
			 * if(pDTO!= null){ distributorType = "3"; sharingProportion =
			 * pDTO.getSharingProportion(); flag = true ; } if(!flag){ //服务站
			 * ServiceStationInfo sInfo =
			 * serviceStationInfoDao.selectByMobilePhone
			 * (existInfo.getMobilePhone()); if(sInfo!= null){ distributorType =
			 * "6"; sharingProportion = sInfo.getSharingProportion(); flag =
			 * true ; } } if(!flag){//都不是，则为普通推广者 distributorType = "0"; } }
			 */

			if (StringUtils.isNotBlank(existInfo.getRecommendCode())) {
				// 查询是否已经新增了推广者
                DistributorInfo disInfo = distributorInfoDao.queryByUserId(existInfo.getId());
                if(null == disInfo){
					// 新增普通推广者到分销商表中
					disInfo = new DistributorInfo();
					disInfo.setUserId(existInfo.getId());
					disInfo.setDistributorName(existInfo.getUserName());
                    disInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    disInfo.setShareCode(existInfo.getRecommendCode());
					disInfo.setDistributorType(distributorType);
					disInfo.setDisabledFlag(0);
					disInfo.setSharingProportion(sharingProportion);

					int count = distributorInfoDao.insert(disInfo);
					if (count == 1) {
						map.put("err_code", 0);
						map.put("err_msg", "查询：推广码已经存在");
						map.put("recommendCode", existInfo.getRecommendCode());
					} else {
						map.put("err_code", 1);
						map.put("err_msg", "新增推广者失败");
						map.put("recommendCode", null);
					}
				} else {
					map.put("err_code", 0);
					map.put("err_msg", "查询：推广码已经存在");
					map.put("recommendCode", existInfo.getRecommendCode());
				}
			} else {
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("num", 8);
                paramMap.put("count", 1);
                String recommendCode = userInfoDao.generateRecommendCode(paramMap);
				info.setRecommendCode(recommendCode);
				int result = userInfoDao.updateById(info);
				if (result == 1) {
					// 新增普通推广者到分销商表中
					DistributorInfo disInfo = new DistributorInfo();
					disInfo.setUserId(existInfo.getId());
					disInfo.setDistributorName(existInfo.getUserName());
                    disInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    disInfo.setShareCode(recommendCode);
					disInfo.setDistributorType(distributorType);
					disInfo.setDisabledFlag(0);
					disInfo.setSharingProportion(sharingProportion);

					int count = distributorInfoDao.insert(disInfo);
					if (count == 1) {
						map.put("err_code", 0);
						map.put("err_msg", "新增推广码成功");
						map.put("recommendCode", recommendCode);
					} else {
						map.put("err_code", 1);
						map.put("err_msg", "新增推广者失败");
						map.put("recommendCode", null);
					}
				}
			}
		} else {
			map.put("err_code", -1);
			map.put("err_msg", "用户信息不存在");
		}
		return map;
	}
    
    /**
     * @author Javin
     * @date 2017年8月31日
     * @desc 分页查询管理员
     */
	@Override
	public Object queryManagerPage(UserInfo info) {
		return null;
	}

	@Override
	public Object isPartnerByRecommendCode(String recommendCode) {
		Map<String, Object> map = new HashMap<String, Object>();

		UserInfo info = userInfoDao.isPartnerByRecommendCode(recommendCode);
		if (info != null) {
			map.put("err_code", 0);// 是合作方的
			map.put("er_msg", "是合作方或其推广人");
		} else {
			map.put("err_code", 1);
			map.put("err_msg", "不是合作方或其推广人");
		}
		return map;
	}

	@Override
	public Object isTeacherByScanShareCode(String recommendCode) {
		Map<String, Object> map = new HashMap<String, Object>();

		UserInfo info = userInfoDao.isTeacherByScanShareCode(recommendCode);
		if (info != null) {
			map.put("err_code", 0);// 是合作方的
			map.put("er_msg", "是后台给到导师的二维码");
		} else {
			map.put("err_code", 1);
			map.put("err_msg", "不是后台给到导师的二维码");
		}
		return map;
	}

	@Override
	public Object isExistSelectByUserName(String userName) {
		Map<String, Object> map = new HashMap<String, Object>();

		List<UserInfo> userList = userInfoDao.selectByUserName(userName);
		if (userList != null && userList.size() > 0) {
			map.put("err_code", 0);
			map.put("err_msg", "该用户存在");
		} else {
			map.put("err_code", 1);
			map.put("err_msg", "该用户不存在，请确认用户的昵称");
		}

		return map;
	}

	@Override
	public Object queryPageTeacherWithRecord(UserInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();

		List<UserInfo> userList = userInfoDao.queryPageTeacherWithRecordAndCourse(info);
		int total = userList.size();
		if (total == 0) {
			map.put("err_code", 1);
			map.put("err_msg", "没有数据");
		} else {
			map.put("err_code", 0);
			map.put("rows", userList);
		}
		return map;
	}

	@Override
	public Object updatePriceById(UserInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();
		int row = userInfoDao.updateById(info);
		if (row != 1) {
			return "error";
		}
		return "ok";
	}


	@Override
	public Object queryPageUser(UserInfo userInfo,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		//全站用户数
        int totalCount = userInfoDao.countUserInfo(userInfo);

		userInfo.setRoleType(1); //普通用户  
		List<UserInfo> list = userInfoDao.queryPageUser2(userInfo);
		map.put("total", userInfoDao.countUser(userInfo));
		map.put("rows", list);
		map.put("totalCount", totalCount);
		return map;
	}

	@Override
	public Object exportExl(UserInfo userInfo, HttpServletResponse response,HttpSession session){
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		// GET请求乱码
		if (StringUtils.isNotBlank(userInfo.getUserName())) {
			userInfo.setUserName(userInfo.getUserName());
		}
		if (StringUtils.isNotBlank(userInfo.getProvince())) {
			userInfo.setProvince(userInfo.getProvince());
		}
		if (StringUtils.isNotBlank(userInfo.getUserName())) {
			userInfo.setUserName("%"+userInfo.getUserName()+"%");
		}
		userInfo.setRoleType(1); //普通用户
		List<UserInfo> data = userInfoDao.queryPageUser2(userInfo);
		if (data == null || data.size() == 0) {
			map.put("err_code", 404);
			map.put("err_msg", "无可导出数据");
			return map;
		}
		try {
			ExcelUtil.writeExcel(response, "用户"+DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)+".xls", data, UserInfo.class);
			map.put("err_code", 200);
			map.put("err_msg", "导出成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "导出失败");
		}
		return map;
	}

	@Override
	public Object addAdminUser(UserInfo userInfo,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (loginUser.getRoleId().intValue()!= RoleInfoEnum.SYS_ADMIN.getRoleId()) {
			map.put("err_code", 101);
			map.put("err_msg", "没有权限访问");
			return map;
		}
		if (StringUtils.isBlank(userInfo.getLoginCode())) {
			map.put("err_code", 401);
			map.put("err_msg", "账号不能为空");
			return map;
		}
		if (StringUtils.isBlank(userInfo.getPasswordSrc())) {
			map.put("err_code", 402);
			map.put("err_msg", "密码不能为空");
			return map;
		}
		if (!RegexUtil.checkPwd(userInfo.getPasswordSrc())) {
			map.put("err_code", 403);
			map.put("err_msg", "密码必须为6-12位,英文和数字的组合");
			return map;
		}
		
		//账号唯一性验证
		if (loginCodeValidate(userInfo.getLoginCode(), "").equals("ok")) {
			userInfo.setPassword(MD5Encrypt.encryptByMD5(userInfo.getPasswordSrc()));
			userInfo.setRegisterDate(new Date().getTime());
			int result = userInfoDao.insertSelective(userInfo);
			if (result > 0) {
				map.put("err_code", 200);
				map.put("err_msg", "添加成功");
			}else {
				map.put("err_code", 500);
				map.put("err_msg", "添加失败");
			}
		}else {
			map.put("err_code", 400);
			map.put("err_msg", "账号已被使用");
		}
		return map;
	}

	@Override
	public Object queryAdminUserByPage(UserInfo userInfo,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (loginUser.getRoleId().intValue() != RoleInfoEnum.SYS_ADMIN.getRoleId()) {
			map.put("err_code", 101);
			map.put("err_msg", "没有权限访问");
			return map;
		}
		userInfo.setRoleType(0); //管理员
		List<UserInfo> list = userInfoDao.queryPageUser2(userInfo);
		List<AdminUserDto> result = new ArrayList<AdminUserDto>();
		StringBuffer sb = new StringBuffer();

		for (UserInfo info : list) {
			List<MenuInfo> mList = menuInfoDao.queryMenuByRoleId(info
					.getRoleId()); // 用户的所有菜单
			for (MenuInfo menuInfo : mList) {
				if (menuInfo.getMenuLevel() == 1) {
					sb.append(menuInfo.getMenuName() + ":");
					for (MenuInfo menuInfo2 : mList) {
						if (menuInfo2.getSuperMenu().equals(
								menuInfo.getMenuCode())) {
							sb.append(menuInfo2.getMenuName() + ",");
						}
					}
					sb.deleteCharAt(sb.length() - 1);
					sb.append("</br>");
				}
			}
			AdminUserDto adminUserDto = new AdminUserDto();
			adminUserDto.setLoginCode(info.getLoginCode());
			adminUserDto.setUserName(info.getUserName());
			adminUserDto.setUserId(info.getId() + "");
			adminUserDto.setRegisterTime(new Date(info.getRegisterDate()));
			adminUserDto.setRoleName(info.getRoleName());
			adminUserDto.setDisableFlag(info.getDisableFlag() + "");
			adminUserDto.setAuthority(sb.toString());
			sb.setLength(0);
			result.add(adminUserDto);
		}
		map.put("rows", result);
		map.put("total", userInfoDao.countUser(userInfo));
		return map;
	}

	@Override
	public Object loginAdmin(UserInfo userInfo,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
			
		 	if (userInfo.getLoginCode()==null || "".equals(userInfo.getLoginCode())) {
	           map.put("err_code", 4001);
	           map.put("err_msg", "输入账号为空");
	           return map;
	        }
		 	List<UserInfo> list = userInfoDao.loginAdmin(userInfo.getLoginCode());
		 	
	     	if(null == list || list.size() == 0){
	     	   map.put("err_code", 4002);
	           map.put("err_msg", "账号不存在或角色不存在");
	           return map;
	     	}else if(list.size() > 1){
	     		 map.put("err_code", 4002);
	     		 map.put("err_msg", "用户信息个数为"+list.size()+",请联系联系管理员");
	           return map;
	     	}else{
	     		UserInfo existUser = list.get(0);
	     		if(null == existUser.getPassword() || existUser.getPassword().length == 0){
	     			 map.put("err_code", 4003);
	     			 map.put("err_msg", "密码不存在、请重置密码");
	     			 return map;
	     		}
	     		//密码不匹配
	     		if(!MD5Encrypt.validatePassword(userInfo.getPasswordSrc(), existUser.getPassword())){
	     			 map.put("err_code", 4003);
	     			 map.put("err_msg", "密码错误");
	     			 return map;
	     		}
	     		//判断角色是否被禁用
				RoleInfo role = roleInfoDao.isDisabled(existUser);
				if (role==null) {
				   map.put("err_code", 400);
			       map.put("err_msg", "该用户角色已被禁用,请联系系统管理员");
			       return map;
				}
	     		existUser.setSessionId(userInfo.getSessionId());
	     		int result = userInfoDao.updateSession2(existUser);
	     		if(result == 1){
	     			 RoleInfo roleInfo = roleInfoBo.queryById(existUser.getRoleId());
	     			 existUser.setRoleName(roleInfo.getRoleName());
	     			 map.put("err_code", 200);
	     			 map.put("err_msg", "登录成功");
	     			 map.put("info", existUser);
	     			 session.setAttribute(GlobalConstant.USER_INFO, existUser);
	     			 return map;
	     		}else{
	     			 map.put("err_code", 4004);
	     			 map.put("err_msg", "登录错误");
	     			 return map;
	     		}
	     	}
	}

    @Override
    public Object queryTeacherInfoWithRecord(UserInfo info) {
        Map<String, Object> map = new HashMap<String, Object>();

        UserInfo userInfo = userInfoDao.queryTeacherInfoWithRecord(info);
        if (userInfo == null) {
            map.put("err_code", 1);
            map.put("err_msg", "没有数据");
        } else {
            map.put("err_code", 0);
            map.put("info", userInfo);
        }
        return map;
    }

    @Override
    public Object updateBankcardByInfo(UserInfo userInfo, HttpSession session) {
        UserInfo globalUserInfo = ((UserInfo) session.getAttribute(GlobalConstant.USER_INFO));
        Map<String, Object> map = new HashMap<String, Object>();
        String bankCard = userInfo.getBankCard();
        String bankCardOwner = userInfo.getBankCardOwner();
        if (globalUserInfo == null) {
            map.put("err_code", 2);
            map.put("err_msg", "用户没有登录");
            return map;
        }
        UserInfo userBankCardInfo = userInfoDao.queryBankCardInfoById(globalUserInfo);

        if (bankCard == null) {
            map.put("err_code", 3);
            map.put("err_msg", "银行卡号没有数据");
            return map;
        }
        if (bankCard.equals(userBankCardInfo.getBankCard())) {
            map.put("err_code", 4);
            map.put("err_msg", "银行卡号不能与之前的相同");
            return map;
        }
        if (StringUtils.isBlank(bankCardOwner)) {
            map.put("err_code", 5);
            map.put("err_msg", "持有者姓名为空");
            return map;
        }
        userInfo.setCardModifyDate(new Timestamp(System.currentTimeMillis()));
        int row = userInfoDao.updateById(userInfo);
        if (row > 0) {
            map.put("err_code", 0);
            map.put("err_msg", "修改成功");
        } else {
            map.put("err_code", 1);
            map.put("err_msg", "修改失败");
        }
        return map;
    }
    
    @Override
    public Object queryBankCardInfoById(UserInfo userInfo) {
        Map<String, Object> map = new HashMap<String, Object>();
        UserInfo userInfo1 = userInfoDao.queryBankCardInfoById(userInfo);
        if(null == userInfo1){
        	map.put("err_code", ResponseCode.USER_ERROR.getCode());
        	map.put("err_msg", ResponseCode.USER_ERROR.getDesc());
        	return map;
        }

        if (userInfo1.getCardModifyDate() == null) {
            userInfo1.setCardModifyAllow(1);
        } else {
            Calendar cal = Calendar.getInstance();
            Calendar cal2 = Calendar.getInstance();
            cal2.setTime(userInfo1.getCardModifyDate());
            int cardMonth = cal2.get(Calendar.MONTH) + 1;
            int nowMonth = cal.get(Calendar.MONTH) + 1;
            int year = cal2.get(Calendar.YEAR);

            if (cardMonth == nowMonth && year == cal.get(Calendar.YEAR)) {
                userInfo1.setCardModifyAllow(0);//0代表不能修改
            } else {
                userInfo1.setCardModifyAllow(1);//1代表能修改
            }
        }

        if (StringUtils.isNotBlank(userInfo1.getBankCard())) {
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("info", userInfo1);
        } else {
            map.put("err_code", 1);
            map.put("err_msg", "查询失败");
        }
        return map;
    }
    
	@Override
	public Object updateAdminUserById(UserInfo userInfo,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (loginUser.getRoleId().intValue() != RoleInfoEnum.SYS_ADMIN.getRoleId()) {
			map.put("err_code", 101);
			map.put("err_msg", "没有权限访问");
			return map;
		}
		if (StringUtils.isBlank(userInfo.getLoginCode())) {
			map.put("err_code", 401);
			map.put("err_msg", "账号不能为空");
			return map;
		}
		if (userInfo.getRoleId()==null) {
			map.put("err_code", 402);
			map.put("err_msg", "请勾选角色");
			return map;
		}
//		if (StringUtils.isBlank(userInfo.getPasswordSrc())) {
//			map.put("err_code", 402);
//			map.put("err_msg", "密码不能为空");
//			return map;
//		}
		//账号唯一性验证
		if (loginCodeValidate(userInfo.getLoginCode(), userInfo.getId()+"").equals("ok")) {
			//userInfo.setPassword(MD5Encrypt.encryptByMD5(userInfo.getPasswordSrc())); //密码不可修改
			int result = userInfoDao.updateAdminUserById(userInfo);
			if (result > 0) {
				map.put("err_code", 200);
				map.put("err_msg", "添加成功");
			}else {
				map.put("err_code", 200);
				map.put("err_msg", "添加失败");
			}
		}else {
			map.put("err_code", 400);
			map.put("err_msg", "账号已被使用");
		}
		return map;
	}

	@Override
	public Object queryMyPraise(UserInfo info) {
		// TODO Auto-generated method stub
		Map<String, Object> map = new HashMap<String, Object>();
        if (info.getId() == null || 0 == info.getId()) {
            map.put("err_code", ResponseCode.USER_ERROR.getCode());
            map.put("err_msg", ResponseCode.USER_ERROR.getDesc());
            return map;
        }
        
		List<UserInfo> list = userInfoDao.queryMyPraise();
		if(list.size()>0){
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("list" , list);
			
		}else{
			map.put("err_code", 1);
			map.put("err_msg", "查询失败");
			map.put("list" , null);
		}
		
		//个人排名情况
		UserInfo myInfo = userInfoDao.queryMyPraiseById( info.getId());
		map.put("rows", myInfo);//当前用户的排名信息
		return map;
	}

    @Override
    public UserInfo queryByWeixinUnionid(String weixinOpenid) {
        return userInfoDao.queryByWeixinUnionid(weixinOpenid);
    }

	@Override
	public Object queryMyHappiness(UserHappinessDto dto) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (dto.getUserId()==null) {
			map.put("err_code", 400);
			map.put("err_msg", "userId不能为空");
			return map;
		}
		List<UserHappinessDto> rankingList = null;
		UserHappinessDto myHappinessDto = null;
		//构建查询条件
		UserHappinessDto vo = new UserHappinessDto();
		vo.setPage(dto.getPage());
		vo.setRows(dto.getRows());
		
		if (StringUtils.isNotBlank(dto.getDate())) { //前端传date则是查今天,没传则查历史总
			//今天的幸福
			vo.setDate(dto.getDate());
			rankingList = (List<UserHappinessDto>) userInfoDao.queryHappinessRank(vo);
			vo.setUserId(dto.getUserId());
			myHappinessDto = userInfoDao.queryHappinessRank(vo).get(0);
		}else {
			//稳稳的幸福
			vo.setDate(null);
			vo.setUserId(null);
			rankingList = (List<UserHappinessDto>) userInfoDao.queryHappinessRank(vo);
			vo.setUserId(dto.getUserId());
			myHappinessDto = userInfoDao.queryHappinessRank(vo).get(0);
		}
	
		if (rankingList!=null && rankingList.size()>0) {
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "无数据");
		}
		map.put("myHappiness", myHappinessDto);
		map.put("rankingList", rankingList);
		return map;
	}

    @Override
    public int txAddUserInfo(UserInfo userInfo) {
        return userInfoDao.insertSelective(userInfo);
    }

	@Override
	public Object queryMyHappinessChart(UserHappinessDto dto) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (dto.getUserId()==null) {
			map.put("err_code", 400);
			map.put("err_msg", "userId不能为空");
			return map;
		}
		UserHappinessDto todayHappiness = null;
		List<Map<String, Object>> resultList = new ArrayList<>();
//		Map<String,Object> result = new TreeMap<>(new Comparator<String>() {
//			@Override
//			public int compare(String str1, String str2) {
//				return -(str1.compareTo(str2));
//			}
//		});
		//前端传来的今天的日期
		String today = dto.getDate();
		for (int i = 0; i <= 7; i++) {
			Map<String, Object> result = new HashMap<>();
			String date = DateUtil.checkOption("pre", today, i,DateUtil.YEAR_MONTH_DAY);
			dto.setDate(date);
			todayHappiness = happinessInfoDao.queryHappinessByUserIdAndDate(dto);
			result.put("date", date);
			result.put("value", todayHappiness.getTotalLove());
			resultList.add(result);
		}
		return resultList;
	}

	@Override
	public Map<String, Object> loginWeb(UserInfo userInfo) {
		Map<String, Object> map = new HashMap<String,Object>();
		if(StringUtils.isBlank(userInfo.getLoginCode()) || StringUtils.isBlank(userInfo.getPasswordSrc())){
			map.put("err_code", ResponseCode.ACOUNT_OR_PASS_ERR.getCode());
			map.put("err_msg", ResponseCode.ACOUNT_OR_PASS_ERR.getDesc());
			return map;
		}
		UserInfo userInfoInDB = userInfoDao.login(userInfo.getLoginCode());
		if(null == userInfoInDB){
			map.put("err_code", ResponseCode.USER_ERROR.getCode());
			map.put("err_msg", ResponseCode.USER_ERROR.getDesc());
			return map;
		}
		if(userInfoInDB.getPassword() == null){
			map.put("err_code", "405");
			map.put("err_msg", "用户还没设置密码");
			return map;
		}
		if(!MD5Encrypt.validatePassword(userInfo.getPasswordSrc(), userInfoInDB.getPassword())){
			map.put("err_code", ResponseCode.ACOUNT_OR_PASS_ERR.getCode());
			map.put("err_msg", ResponseCode.ACOUNT_OR_PASS_ERR.getDesc());
			return map;
        }
		userInfoInDB.setSessionId(userInfo.getSessionId());
        int updated = userInfoDao.updateSession2(userInfoInDB);
        if(updated == 1){
        	userInfoInDB.setPasswordSrc(null);
        	map.put("err_code", ResponseCode.SUCCESS.getCode());
			map.put("err_msg", ResponseCode.SUCCESS.getCode());
			map.put("userInfo", userInfoInDB);
			return map;
        }
		return map;
	}

    /*
    * 明人 1.3.1 学习记录
    * */
    @Override
    public Object queryStudyRecord(UserHappinessDto dto, HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        UserInfo userInfo = ((UserInfo) session.getAttribute(GlobalConstant.USER_INFO));
        if (null == userInfo) {
            map.put("err_code", ResponseCode.USER_ERROR.getCode());
            map.put("err_msg", ResponseCode.USER_ERROR.getDesc());
            return map;
        }

        dto.setShareCode(userInfo.getRecommendCode());

        List<UserHappinessDto> list = userInfoDao.queryStudyRecord(dto);
        UserHappinessDto userHappinessDto = userInfoDao.queryTotalStudyRecord(dto);

        for (UserHappinessDto userHappinessDto2 : list) {
            int hour = userHappinessDto2.getLastingStudy() / 3600;
            int min = (userHappinessDto2.getLastingStudy() - 3600 * hour) / 60;
            userHappinessDto2.setLastingStudyStr(hour + "小时" + min + "分钟");
        }

        if (userHappinessDto.getLearningSessions() == null) {
            map.put("TotalNum", 0);
            map.put("LearningSessions", null);
            map.put("LastingStudy", null);
            map.put("CumulationSignCount", null);
            map.put("TotalLove", null);
            map.put("TotalScore", null);
        } else {
            map.put("TotalNum", userHappinessDto.getTotalNum());
            map.put("LearningSessions", userHappinessDto.getLearningSessions());
            map.put("LastingStudy", userHappinessDto.getLastingStudy() / 3600);
            map.put("CumulationSignCount", userHappinessDto.getCumulationSignCount());
            map.put("TotalLove", userHappinessDto.getTotalLove());
            map.put("TotalScore", userHappinessDto.getTotalScore());
        }


        map.put("rows", list);
        map.put("total", userHappinessDto.getTotalNum());
        map.put("err_code", 0);
        map.put("err_msg", "查询成功");
        return map;
    }

    @Override
    public Object exportStudyRecord(UserHappinessDto dto, HttpServletResponse response, HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        if (null == loginUser) {
            map.put("err_code", ResponseCode.USER_ERROR.getCode());
            map.put("err_msg", ResponseCode.USER_ERROR.getDesc());
            return map;
        }

        String recommendCode = loginUser.getRecommendCode();
        if (recommendCode != null) {
            dto.setShareCode(recommendCode);
        }
        dto.setMessageString("1");

        List<UserHappinessDto> list = userInfoDao.queryStudyRecord(dto);
        if (list == null || list.size() == 0) {
            map.put("err_code", 404);
            map.put("err_msg", "无可导出数据");
            return map;

        }
        SchoolInfo schoolInfo = null;
        if (loginUser.getSchoolId() != null) {
            schoolInfo = schoolInfoDao.querySchoolByRecommendCode(loginUser.getRecommendCode());
        }
        for (UserHappinessDto userHappinessDto : list) {
            if (schoolInfo != null) {
                userHappinessDto.setSchoolName(schoolInfo.getSchoolName());
            }

            int hour = userHappinessDto.getLastingStudy() / 3600;
            int min = (userHappinessDto.getLastingStudy() - 3600 * hour) / 60;
            userHappinessDto.setLastingStudyStr(hour + "小时" + min + "分钟");
        }

        try {
            ExcelUtil.writeExcel(response, "扫码日志" + DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR) + ".xls", list, UserHappinessDto.class);
            map.put("err_code", 200);
            map.put("err_msg", "导出成功");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("err_code", 500);
            map.put("err_msg", "导出失败");
        }
        return map;
    }

	@Override
	public Object queryInfoByUserId(UserInfo info,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo ui = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        if (ui == null || info.getId() == null || info.getId() == 0) {
            //游客状态
            map.put("err_code", -1);
			map.put("err_msg", "当前用户为游客");
			map.put("goodNum", 0);
			map.put("integralBalance", 0);
			map.put("totalIncome", 0);
			map.put("totalQA", 0);
			map.put("ieNum", 0);
			map.put("dividedMoney", 0);
			map.put("newsNum", 0);
			return map;
		}
		
		try {
			QuestionComment comment = new QuestionComment();
			comment.setUserId(info.getId());
			Map<String, Object> rMap = (Map<String, Object>) questionCommentBo.querySumGoodNumByUserId(comment, session);
			//获赞
			map.put("goodNum", rMap.get("sumGoodNum"));
			//积分
			int integralBalance = userInfoDao.queryIntegralBalanceByUserId(info.getId());
			map.put("integralBalance",integralBalance);
			//收入(推广收入+问答收入)
			map.put("totalIncome", ((BigDecimal)rMap.get("disTotalMoney")).add((BigDecimal) ((Map<String, Object>)rMap.get("rows")).get("total")));
			//问答
			int totalAnswer = questionCommentDao.countMyQAPageByUserId(info.getId());
			QuestionInfo question = new QuestionInfo();
            question.setUserId(info.getId());
            int totalQuestion = questionInfoDao.countMyQAPageByUserId(question);
            map.put("totalQA", totalAnswer+totalQuestion);
			//卡券
			IntegralExchangedLogDTO dto = new IntegralExchangedLogDTO();
			dto.setUserId(info.getId());
			int ieNum = integralExchangedLogDao.countByUserId(dto);
			map.put("ieNum", ieNum);
			//推广(推广收入)
			map.put("dividedMoney", (BigDecimal)rMap.get("disTotalMoney"));
			//消息(未读条数)
			int newsNum = messageInfoDao.selectNotReadMsgCountByUserId(info.getId());
			map.put("newsNum", newsNum);
            //所有没读消息数
			MessageInfo mInfo = new MessageInfo();
			mInfo.setUserId(info.getId());
            int totalUnreadNum = questionCommentDao.queryTotalUnReadNumByCommentedId(mInfo);
            int totalUnreadGoodNum = questionCommentDao.queryTotalUnreadGoodNumByCommentedId(mInfo);
            int totalUnreadRecordNum = questionCommentDao.queryTotalUnreadRecordNumByCommentedId(info.getId());
            int allMessage = totalUnreadNum + totalUnreadGoodNum + totalUnreadRecordNum + newsNum;
            map.put("allUnRead", allMessage);

            CoursePackageVip vip = new CoursePackageVip();
            VideoVip videoVip = new VideoVip();
            vip.setUserId(ui.getId());
            videoVip.setUserId(ui.getId());

            int pay_course = coursePackageVipDao.queryCountUserPaidCPByUserid(vip);
            int pay_weclass = videoVipDao.countHasPurchase(videoVip);
            int has_purchase = pay_course + pay_weclass;

            map.put("courseCount", has_purchase);
            map.put("err_code", 200);
            map.put("err_msg", "查询成功");
        } catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "查询失败");
		}
		return map;
	}

	@Override
	public Object queryIntegralBalanceByUserId(Integer userId) {
		return userInfoDao.queryIntegralBalanceByUserId(userId);
	}

	@Override
	public Object editMobilePhoneById(UserInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isBlank(info.getMobilePhone())) {
			map.put("err_code", 101);
			map.put("err_msg", "手机号码为空");
			return map ;
		}
		if(info.getId() == null){
			map.put("err_code", 102);
			map.put("err_msg", "用户id为空");
			return map ;
		}
		UserInfo ui = userInfoDao.queryByMobilePhone(info.getMobilePhone()) ;
		if(ui != null && ui.getId().intValue() != info.getId().intValue()){
			map.put("err_code", 103);
			map.put("err_msg", "该手机号码已被使用");
			return map ;
		}
		UserInfo uuii = userInfoDao.queryById(info.getId()) ;
		//如果是服务站，则修改服务站表的手机号码
		if(uuii !=null && uuii.getRoleId() == RoleInfoEnum.SERVICE_SCHOOL_ADMIN.getRoleId() 
				|| uuii.getRoleId()== RoleInfoEnum.SERVICE_ADMIN.getRoleId()){
			ServiceStationInfo sss =new ServiceStationInfo() ;
			sss.setId(uuii.getStationId());
			sss.setStationMobilePhone(info.getMobilePhone());
			serviceStationInfoDao.updateById(sss);
		}
		int row = userInfoDao.updateById(info) ;
		if(row == 1){
			map.put("err_code", 200);
			map.put("err_msg", "更换手机号码成功");
			return map ;
		}else{
			map.put("err_code", 500);
			map.put("err_msg", "更换手机号码败");
			return map ;
		}
	}

    //智慧型
    @Override
    public Object queryWisdomUser(UserInfo info) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<UserInfo> wisdomUserDaily = userInfoDao.queryWisdomUserDaily(info);//智慧

        //显示全站最新的回帖内容及其发布者，来源帖子标题
        QuestionInfo questionInfo = new QuestionInfo();
        questionInfo.setPage(1);
        questionInfo.setRows(1);
        List<QuestionCommentDto> list = questionCommentDao.quesyNewTextComment(questionInfo);

        map.put("list", list);
        int size = wisdomUserDaily.size();
        if (size == 3) {
            map.put("err_code", 200);
            map.put("err_msg", "查询数据成功");
            map.put("wisdom", wisdomUserDaily);
            return map;
        } else {
            wisdomUserDaily = userInfoDao.queryWisdomUserAll(info);
            map.put("err_code", 200);
            map.put("err_msg", "查询数据成功");
            map.put("wisdom", wisdomUserDaily);
            return map;
        }
    }

    //幸福型
    @Override
    public Object queryHappinessRank(UserHappinessDto dto) {
        Map<String, Object> map = new HashMap<String, Object>();

        SimpleDateFormat sim = new SimpleDateFormat(
                "yyyy-MM-dd");
        String format = sim.format(new Date());
        List<UserHappinessDto> rankingList = null;
        dto.setDate(format);
        //今天的幸福
        rankingList = (List<UserHappinessDto>) userInfoDao.queryHappinessRankWithoutTeacher(dto);
        if (rankingList == null || rankingList.size() == 0) { //前端传date则是查今天,没传则查历史总
            //历史
            dto.setDate(null);
            rankingList = (List<UserHappinessDto>) userInfoDao.queryHappinessRankWithoutTeacher(dto);
        }

        //显示全站最新的【课程评价】内容及来源课程名称
        //处理乱码
        CoursePackageCommentInfo coursePackageCommentInfo = new CoursePackageCommentInfo();
        coursePackageCommentInfo.setPage(1);
        coursePackageCommentInfo.setRows(1);
        List<CoursePackageCommentInfo> list = coursePackageCommentInfoDao.selectPageList(coursePackageCommentInfo);

        if (null != rankingList && rankingList.size() > 0) {
            map.put("err_code", 200);
            map.put("err_msg", "查询成功");
            map.put("happiness", rankingList);
            map.put("list", list);
        }
        return map;
    }

    //学习型
    @Override
    public Object queryStudyUser(UserInfo info) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<UserInfo> studyUserDaily = userInfoDao.queryStudyUserDaily();

        //显示全站最新的微课学习笔记【微课留言】及来源微课名称
        VideoCommentInfo videoComment = new VideoCommentInfo();
        videoComment.setSortType(1);
        videoComment.setStatus(0);
        videoComment.setPage(1);
        videoComment.setRows(1);
        List<VideoCommentInfo> videoCommentInfos = videoCommentInfoDao.queryPageVideoCommentInfo(videoComment);
        map.put("list", videoCommentInfos);

        int size = studyUserDaily.size();
        if (size == 3) {
            map.put("err_code", 200);
            map.put("err_msg", "查询数据成功");
            map.put("study", studyUserDaily);
            return map;
        } else {
            UserVideoRel userVideoRel = new UserVideoRel();
            userVideoRel.setRows(3);
            userVideoRel.setPageStart(0);
            List<StundentRankingDTO> list = userVideoRelDao.queryStudentsRankingByUserId(userVideoRel);
            if (null != list && list.size() > 0) {
                map.put("err_code", 200);
                map.put("err_msg", "查询成功");
                map.put("study", list);
            } else {
                map.put("err_code", 201);
                map.put("err_msg", "查询无数据");
                map.put("study", null);
            }
            return map;
        }
    }

    //用心型
    @Override
    public Object queryKeepDayRankingList(UserInfo info) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<SignInKeepDayDTO> signInKeepDayDTOS = userVideoRelDao.queryKeepDayRankingListWithoutTeacher();//签到

        //随机显示全站的微课学习笔记【微课留言】及来源微课名称
        VideoCommentInfo videoComment = new VideoCommentInfo();
        videoComment.setSortType(2);
        videoComment.setStatus(0);
        videoComment.setPage(1);
        videoComment.setRows(1);
        List<VideoCommentInfo> videoCommentInfos = videoCommentInfoDao.queryPageVideoCommentInfo(videoComment);
        map.put("list", videoCommentInfos);

        if (null != signInKeepDayDTOS && signInKeepDayDTOS.size() > 0) {
            map.put("err_code", 200);
            map.put("err_msg", "查询成功");
            map.put("sign_in", signInKeepDayDTOS);
        }
        return map;
    }


    //幸福墙
    @Override
    public Object queryHappinessWall(UserInfo info) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<UserInfo> list = userInfoDao.queryHappinessWall(info);//签到

        if (null != list && list.size() > 0) {
            map.put("err_code", 200);
            map.put("err_msg", "查询成功");
            map.put("rows", list);
        }
        return map;
    }

	@Override
	public Object queryPaidActivityByUserId(HttpSession session, Integer page,
			Integer rows) {
        UserInfo userInfo = ((UserInfo) session.getAttribute(GlobalConstant.USER_INFO));
        //未登录直接返回
        if (null==userInfo) {
			return ResultUtil.success(null);
		}
        PageHelper.startPage(page, rows);
        List<ActivityPaidDTO> list = activitySignupInfoDao.queryPageByUserId(userInfo.getId());
		return ResultUtil.success(list);
	}

	@Override
	public Object downLoadHeadImg(UserInfo info ,Map<String , Object> map) {
		//设置picName的值（使用微信头像）
        String url = String.format(ConstantsUtil.getProperty("saveHeadImgURL"), info.getHeadImgUrl());
		String s = HttpUtil.doPost(url, null);
        if (StringUtils.isNotBlank(s) && (!s.equals("error")) && !s.contains("nginx")) {
            s = s.replaceAll("\r|\n|\"", "");
            info.setPicName(s);
            userInfoDao.updateById(info) ;
            
            map.put("data", s) ;
        }
        map.put("err_code", "200") ;
        map.put("err_msg", "成功") ;
        
		return map;
	}

}
